code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.authenticator.testability; import android.content.Context; import android.content.Intent; /** * Listener which is invoked when an attempt is made to launch an {@link android.app.Activity} via * {@link Context#startActivity(Intent)} or * {@link android.app.Activity#startActivityForResult(Intent, int)}. * The listener can decide whether to proceed with the launch. * * @author klyubin@google.com (Alex Klyubin) */ public interface StartActivityListener { /** * Invoked when a launch of an {@link android.app.Activity} is requested. * * @return {@code true} to consume/ignore the request, {@code false} to proceed with the launching * of the {@code Activity}. */ boolean onStartActivityInvoked(Context sourceContext, Intent intent); }
zzhyjun-
src/com/google/android/apps/authenticator/testability/StartActivityListener.java
Java
asf20
1,420
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.authenticator.testability; import android.content.Context; import android.os.Build; import org.apache.http.client.HttpClient; import org.apache.http.client.params.HttpClientParams; import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Factory that creates an {@link HttpClient}. * * @author klyubin@google.com (Alex Klyubin) */ final class HttpClientFactory { /** Timeout (ms) for establishing a connection.*/ // @VisibleForTesting static final int DEFAULT_CONNECT_TIMEOUT_MILLIS = 20 * 1000; /** Timeout (ms) for read operations on connections. */ // @VisibleForTesting static final int DEFAULT_READ_TIMEOUT_MILLIS = 20 * 1000; /** Timeout (ms) for obtaining a connection from the connection pool.*/ // @VisibleForTesting static final int DEFAULT_GET_CONNECTION_FROM_POOL_TIMEOUT_MILLIS = 20 * 1000; /** Hidden constructor to prevent instantiation. */ private HttpClientFactory() {} /** * Creates a new {@link HttpClient}. * * @param context context for reusing SSL sessions. */ static HttpClient createHttpClient(Context context) { HttpClient client; // TODO(klyubin): Remove this complicated code once the minimum target is Froyo. if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ECLAIR_MR1) { try { client = createHttpClientForFroyoAndHigher(context); } catch (Exception e) { throw new RuntimeException("Failed to create HttpClient", e); } } else { client = createHttpClientForEclair(); } configureHttpClient(client); return client; } private static void configureHttpClient(HttpClient httpClient) { HttpParams params = httpClient.getParams(); HttpConnectionParams.setStaleCheckingEnabled(params, false); HttpConnectionParams.setConnectionTimeout(params, DEFAULT_CONNECT_TIMEOUT_MILLIS); HttpConnectionParams.setSoTimeout(params, DEFAULT_READ_TIMEOUT_MILLIS); HttpConnectionParams.setSocketBufferSize(params, 8192); ConnManagerParams.setTimeout(params, DEFAULT_GET_CONNECTION_FROM_POOL_TIMEOUT_MILLIS); // Don't handle redirects automatically HttpClientParams.setRedirecting(params, false); // Don't handle authentication automatically HttpClientParams.setAuthenticating(params, false); } private static HttpClient createHttpClientForFroyoAndHigher(Context context) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { // IMPLEMENTATION NOTE: We create the instance via Reflection API to avoid raising the // target SDK version to 8 because that will cause Eclipse to complain for no good reason. // The code below invokes: // AndroidHttpClient.newInstance(null, getContext()) Class<?> androidHttpClientClass = context.getClassLoader().loadClass("android.net.http.AndroidHttpClient"); Method newInstanceMethod = androidHttpClientClass.getMethod("newInstance", String.class, Context.class); return (HttpClient) newInstanceMethod.invoke(null, null, context); } /** * Creates a new instance of {@code HttpClient} for Eclair where we can't use * {@code android.net.http.AndroidHttpClient}. */ private static HttpClient createHttpClientForEclair() { // IMPLEMENTATION NOTE: Since AndroidHttpClient is not available on Eclair, we create a // DefaultHttpClient with a configuration similar to that of AndroidHttpClient. return new DefaultHttpClient(new BasicHttpParams()); } }
zzhyjun-
src/com/google/android/apps/authenticator/testability/HttpClientFactory.java
Java
asf20
4,425
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.authenticator.testability; import android.content.Intent; import android.preference.PreferenceActivity; /** * Base class for {@link PreferenceActivity} instances to make them more testable. * * @author klyubin@google.com (Alex Klyubin) */ public class TestablePreferenceActivity extends PreferenceActivity { @Override public void startActivity(Intent intent) { StartActivityListener listener = DependencyInjector.getStartActivityListener(); if ((listener != null) && (listener.onStartActivityInvoked(this, intent))) { return; } super.startActivity(intent); } @Override public void startActivityForResult(Intent intent, int requestCode) { StartActivityListener listener = DependencyInjector.getStartActivityListener(); if ((listener != null) && (listener.onStartActivityInvoked(this, intent))) { return; } super.startActivityForResult(intent, requestCode); } }
zzhyjun-
src/com/google/android/apps/authenticator/testability/TestablePreferenceActivity.java
Java
asf20
1,575
/* * Copyright 2009 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.authenticator; import com.google.android.apps.authenticator.AccountDb.OtpType; import com.google.android.apps.authenticator.dataimport.ImportController; import com.google.android.apps.authenticator.howitworks.IntroEnterPasswordActivity; import com.google.android.apps.authenticator.testability.DependencyInjector; import com.google.android.apps.authenticator.testability.TestableActivity; import com.google.android.apps.authenticator2.R; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Vibrator; import android.text.ClipboardManager; import android.text.Html; import android.util.Log; import android.util.TypedValue; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.webkit.WebView; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.Serializable; import java.util.ArrayList; /** * The main activity that displays usernames and codes * * @author sweis@google.com (Steve Weis) * @author adhintz@google.com (Drew Hintz) * @author cemp@google.com (Cem Paya) * @author klyubin@google.com (Alex Klyubin) */ public class AuthenticatorActivity extends TestableActivity { /** The tag for log messages */ private static final String LOCAL_TAG = "AuthenticatorActivity"; private static final long VIBRATE_DURATION = 200L; /** Frequency (milliseconds) with which TOTP countdown indicators are updated. */ private static final long TOTP_COUNTDOWN_REFRESH_PERIOD = 100; /** * Minimum amount of time (milliseconds) that has to elapse from the moment a HOTP code is * generated for an account until the moment the next code can be generated for the account. * This is to prevent the user from generating too many HOTP codes in a short period of time. */ private static final long HOTP_MIN_TIME_INTERVAL_BETWEEN_CODES = 5000; /** * The maximum amount of time (milliseconds) for which a HOTP code is displayed after it's been * generated. */ private static final long HOTP_DISPLAY_TIMEOUT = 2 * 60 * 1000; // @VisibleForTesting static final int DIALOG_ID_UNINSTALL_OLD_APP = 12; // @VisibleForTesting static final int DIALOG_ID_SAVE_KEY = 13; /** * Intent action to that tells this Activity to initiate the scanning of barcode to add an * account. */ // @VisibleForTesting static final String ACTION_SCAN_BARCODE = AuthenticatorActivity.class.getName() + ".ScanBarcode"; private View mContentNoAccounts; private View mContentAccountsPresent; private TextView mEnterPinPrompt; private ListView mUserList; private PinListAdapter mUserAdapter; private PinInfo[] mUsers = {}; /** Counter used for generating TOTP verification codes. */ private TotpCounter mTotpCounter; /** Clock used for generating TOTP verification codes. */ private TotpClock mTotpClock; /** * Task that periodically notifies this activity about the amount of time remaining until * the TOTP codes refresh. The task also notifies this activity when TOTP codes refresh. */ private TotpCountdownTask mTotpCountdownTask; /** * Phase of TOTP countdown indicators. The phase is in {@code [0, 1]} with {@code 1} meaning * full time step remaining until the code refreshes, and {@code 0} meaning the code is refreshing * right now. */ private double mTotpCountdownPhase; private AccountDb mAccountDb; private OtpSource mOtpProvider; /** * Key under which the {@link #mOldAppUninstallIntent} is stored in the instance state * {@link Bundle}. */ private static final String KEY_OLD_APP_UNINSTALL_INTENT = "oldAppUninstallIntent"; /** * {@link Intent} for uninstalling the "old" app or {@code null} if not known/available. * * <p> * Note: this field is persisted in the instance state {@link Bundle}. We need to resolve to this * error-prone mechanism because showDialog on Eclair doesn't take parameters. Once Froyo is * the minimum targetted SDK, this contrived code can be removed. */ private Intent mOldAppUninstallIntent; /** Whether the importing of data from the "old" app has been started and has not yet finished. */ private boolean mDataImportInProgress; /** * Key under which the {@link #mSaveKeyDialogParams} is stored in the instance state * {@link Bundle}. */ private static final String KEY_SAVE_KEY_DIALOG_PARAMS = "saveKeyDialogParams"; /** * Parameters to the save key dialog (DIALOG_ID_SAVE_KEY). * * <p> * Note: this field is persisted in the instance state {@link Bundle}. We need to resolve to this * error-prone mechanism because showDialog on Eclair doesn't take parameters. Once Froyo is * the minimum targetted SDK, this contrived code can be removed. */ private SaveKeyDialogParams mSaveKeyDialogParams; /** * Whether this activity is currently displaying a confirmation prompt in response to the * "save key" Intent. */ private boolean mSaveKeyIntentConfirmationInProgress; private static final String OTP_SCHEME = "otpauth"; private static final String TOTP = "totp"; // time-based private static final String HOTP = "hotp"; // counter-based private static final String SECRET_PARAM = "secret"; private static final String COUNTER_PARAM = "counter"; // @VisibleForTesting public static final int CHECK_KEY_VALUE_ID = 0; // @VisibleForTesting public static final int RENAME_ID = 1; // @VisibleForTesting public static final int REMOVE_ID = 2; // @VisibleForTesting static final int COPY_TO_CLIPBOARD_ID = 3; // @VisibleForTesting static final int SCAN_REQUEST = 31337; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAccountDb = DependencyInjector.getAccountDb(); mOtpProvider = DependencyInjector.getOtpProvider(); // Use a different (longer) title from the one that's declared in the manifest (and the one that // the Android launcher displays). setTitle(R.string.app_name); mTotpCounter = mOtpProvider.getTotpCounter(); mTotpClock = mOtpProvider.getTotpClock(); setContentView(R.layout.main); // restore state on screen rotation Object savedState = getLastNonConfigurationInstance(); if (savedState != null) { mUsers = (PinInfo[]) savedState; // Re-enable the Get Code buttons on all HOTP accounts, otherwise they'll stay disabled. for (PinInfo account : mUsers) { if (account.isHotp) { account.hotpCodeGenerationAllowed = true; } } } if (savedInstanceState != null) { mOldAppUninstallIntent = savedInstanceState.getParcelable(KEY_OLD_APP_UNINSTALL_INTENT); mSaveKeyDialogParams = (SaveKeyDialogParams) savedInstanceState.getSerializable(KEY_SAVE_KEY_DIALOG_PARAMS); } mUserList = (ListView) findViewById(R.id.user_list); mContentNoAccounts = findViewById(R.id.content_no_accounts); mContentAccountsPresent = findViewById(R.id.content_accounts_present); mContentNoAccounts.setVisibility((mUsers.length > 0) ? View.GONE : View.VISIBLE); mContentAccountsPresent.setVisibility((mUsers.length > 0) ? View.VISIBLE : View.GONE); TextView noAccountsPromptDetails = (TextView) findViewById(R.id.details); noAccountsPromptDetails.setText( Html.fromHtml(getString(R.string.welcome_page_details))); findViewById(R.id.how_it_works_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { displayHowItWorksInstructions(); } }); findViewById(R.id.add_account_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addAccount(); } }); mEnterPinPrompt = (TextView) findViewById(R.id.enter_pin_prompt); mUserAdapter = new PinListAdapter(this, R.layout.user_row, mUsers); mUserList.setVisibility(View.GONE); mUserList.setAdapter(mUserAdapter); mUserList.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> unusedParent, View row, int unusedPosition, long unusedId) { NextOtpButtonListener clickListener = (NextOtpButtonListener) row.getTag(); View nextOtp = row.findViewById(R.id.next_otp); if ((clickListener != null) && nextOtp.isEnabled()){ clickListener.onClick(row); } mUserList.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); } }); if (savedInstanceState == null) { // This is the first time this Activity is starting (i.e., not restoring previous state which // was saved, for example, due to orientation change) DependencyInjector.getOptionalFeatures().onAuthenticatorActivityCreated(this); importDataFromOldAppIfNecessary(); handleIntent(getIntent()); } } /** * Reacts to the {@link Intent} that started this activity or arrived to this activity without * restarting it (i.e., arrived via {@link #onNewIntent(Intent)}). Does nothing if the provided * intent is {@code null}. */ private void handleIntent(Intent intent) { if (intent == null) { return; } String action = intent.getAction(); if (action == null) { return; } if (ACTION_SCAN_BARCODE.equals(action)) { scanBarcode(); } else if (intent.getData() != null) { interpretScanResult(intent.getData(), true); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(KEY_OLD_APP_UNINSTALL_INTENT, mOldAppUninstallIntent); outState.putSerializable(KEY_SAVE_KEY_DIALOG_PARAMS, mSaveKeyDialogParams); } @Override public Object onRetainNonConfigurationInstance() { return mUsers; // save state of users and currently displayed PINs } // Because this activity is marked as singleTop, new launch intents will be // delivered via this API instead of onResume(). // Override here to catch otpauth:// URL being opened from QR code reader. @Override protected void onNewIntent(Intent intent) { Log.i(getString(R.string.app_name), LOCAL_TAG + ": onNewIntent"); handleIntent(intent); } @Override protected void onStart() { super.onStart(); updateCodesAndStartTotpCountdownTask(); } @Override protected void onResume() { super.onResume(); Log.i(getString(R.string.app_name), LOCAL_TAG + ": onResume"); importDataFromOldAppIfNecessary(); } @Override protected void onStop() { stopTotpCountdownTask(); super.onStop(); } private void updateCodesAndStartTotpCountdownTask() { stopTotpCountdownTask(); mTotpCountdownTask = new TotpCountdownTask(mTotpCounter, mTotpClock, TOTP_COUNTDOWN_REFRESH_PERIOD); mTotpCountdownTask.setListener(new TotpCountdownTask.Listener() { @Override public void onTotpCountdown(long millisRemaining) { if (isFinishing()) { // No need to reach to this even because the Activity is finishing anyway return; } setTotpCountdownPhaseFromTimeTillNextValue(millisRemaining); } @Override public void onTotpCounterValueChanged() { if (isFinishing()) { // No need to reach to this even because the Activity is finishing anyway return; } refreshVerificationCodes(); } }); mTotpCountdownTask.startAndNotifyListener(); } private void stopTotpCountdownTask() { if (mTotpCountdownTask != null) { mTotpCountdownTask.stop(); mTotpCountdownTask = null; } } /** Display list of user emails and updated pin codes. */ protected void refreshUserList() { refreshUserList(false); } private void setTotpCountdownPhase(double phase) { mTotpCountdownPhase = phase; updateCountdownIndicators(); } private void setTotpCountdownPhaseFromTimeTillNextValue(long millisRemaining) { setTotpCountdownPhase( ((double) millisRemaining) / Utilities.secondsToMillis(mTotpCounter.getTimeStep())); } private void refreshVerificationCodes() { refreshUserList(); setTotpCountdownPhase(1.0); } private void updateCountdownIndicators() { for (int i = 0, len = mUserList.getChildCount(); i < len; i++) { View listEntry = mUserList.getChildAt(i); CountdownIndicator indicator = (CountdownIndicator) listEntry.findViewById(R.id.countdown_icon); if (indicator != null) { indicator.setPhase(mTotpCountdownPhase); } } } /** * Display list of user emails and updated pin codes. * * @param isAccountModified if true, force full refresh */ // @VisibleForTesting public void refreshUserList(boolean isAccountModified) { ArrayList<String> usernames = new ArrayList<String>(); mAccountDb.getNames(usernames); int userCount = usernames.size(); if (userCount > 0) { boolean newListRequired = isAccountModified || mUsers.length != userCount; if (newListRequired) { mUsers = new PinInfo[userCount]; } for (int i = 0; i < userCount; ++i) { String user = usernames.get(i); try { computeAndDisplayPin(user, i, false); } catch (OtpSourceException ignored) {} } if (newListRequired) { // Make the list display the data from the newly created array of accounts // This forces the list to scroll to top. mUserAdapter = new PinListAdapter(this, R.layout.user_row, mUsers); mUserList.setAdapter(mUserAdapter); } mUserAdapter.notifyDataSetChanged(); if (mUserList.getVisibility() != View.VISIBLE) { mUserList.setVisibility(View.VISIBLE); registerForContextMenu(mUserList); } } else { mUsers = new PinInfo[0]; // clear any existing user PIN state mUserList.setVisibility(View.GONE); } // Display the list of accounts if there are accounts, otherwise display a // different layout explaining the user how this app works and providing the user with an easy // way to add an account. mContentNoAccounts.setVisibility((mUsers.length > 0) ? View.GONE : View.VISIBLE); mContentAccountsPresent.setVisibility((mUsers.length > 0) ? View.VISIBLE : View.GONE); } /** * Computes the PIN and saves it in mUsers. This currently runs in the UI * thread so it should not take more than a second or so. If necessary, we can * move the computation to a background thread. * * @param user the user email to display with the PIN * @param position the index for the screen of this user and PIN * @param computeHotp true if we should increment counter and display new hotp */ public void computeAndDisplayPin(String user, int position, boolean computeHotp) throws OtpSourceException { PinInfo currentPin; if (mUsers[position] != null) { currentPin = mUsers[position]; // existing PinInfo, so we'll update it } else { currentPin = new PinInfo(); currentPin.pin = getString(R.string.empty_pin); currentPin.hotpCodeGenerationAllowed = true; } OtpType type = mAccountDb.getType(user); currentPin.isHotp = (type == OtpType.HOTP); currentPin.user = user; if (!currentPin.isHotp || computeHotp) { // Always safe to recompute, because this code path is only // reached if the account is: // - Time-based, in which case getNextCode() does not change state. // - Counter-based (HOTP) and computeHotp is true. currentPin.pin = mOtpProvider.getNextCode(user); currentPin.hotpCodeGenerationAllowed = true; } mUsers[position] = currentPin; } /** * Parses a secret value from a URI. The format will be: * * otpauth://totp/user@example.com?secret=FFF... * otpauth://hotp/user@example.com?secret=FFF...&counter=123 * * @param uri The URI containing the secret key * @param confirmBeforeSave a boolean to indicate if the user should be * prompted for confirmation before updating the otp * account information. */ private void parseSecret(Uri uri, boolean confirmBeforeSave) { final String scheme = uri.getScheme().toLowerCase(); final String path = uri.getPath(); final String authority = uri.getAuthority(); final String user; final String secret; final OtpType type; final Integer counter; if (!OTP_SCHEME.equals(scheme)) { Log.e(getString(R.string.app_name), LOCAL_TAG + ": Invalid or missing scheme in uri"); showDialog(Utilities.INVALID_QR_CODE); return; } if (TOTP.equals(authority)) { type = OtpType.TOTP; counter = AccountDb.DEFAULT_HOTP_COUNTER; // only interesting for HOTP } else if (HOTP.equals(authority)) { type = OtpType.HOTP; String counterParameter = uri.getQueryParameter(COUNTER_PARAM); if (counterParameter != null) { try { counter = Integer.parseInt(counterParameter); } catch (NumberFormatException e) { Log.e(getString(R.string.app_name), LOCAL_TAG + ": Invalid counter in uri"); showDialog(Utilities.INVALID_QR_CODE); return; } } else { counter = AccountDb.DEFAULT_HOTP_COUNTER; } } else { Log.e(getString(R.string.app_name), LOCAL_TAG + ": Invalid or missing authority in uri"); showDialog(Utilities.INVALID_QR_CODE); return; } user = validateAndGetUserInPath(path); if (user == null) { Log.e(getString(R.string.app_name), LOCAL_TAG + ": Missing user id in uri"); showDialog(Utilities.INVALID_QR_CODE); return; } secret = uri.getQueryParameter(SECRET_PARAM); if (secret == null || secret.length() == 0) { Log.e(getString(R.string.app_name), LOCAL_TAG + ": Secret key not found in URI"); showDialog(Utilities.INVALID_SECRET_IN_QR_CODE); return; } if (AccountDb.getSigningOracle(secret) == null) { Log.e(getString(R.string.app_name), LOCAL_TAG + ": Invalid secret key"); showDialog(Utilities.INVALID_SECRET_IN_QR_CODE); return; } if (secret.equals(mAccountDb.getSecret(user)) && counter == mAccountDb.getCounter(user) && type == mAccountDb.getType(user)) { return; // nothing to update. } if (confirmBeforeSave) { mSaveKeyDialogParams = new SaveKeyDialogParams(user, secret, type, counter); showDialog(DIALOG_ID_SAVE_KEY); } else { saveSecretAndRefreshUserList(user, secret, null, type, counter); } } private static String validateAndGetUserInPath(String path) { if (path == null || !path.startsWith("/")) { return null; } // path is "/user", so remove leading "/", and trailing white spaces String user = path.substring(1).trim(); if (user.length() == 0) { return null; // only white spaces. } return user; } /** * Saves the secret key to local storage on the phone and updates the displayed account list. * * @param user the user email address. When editing, the new user email. * @param secret the secret key * @param originalUser If editing, the original user email, otherwise null. * @param type hotp vs totp * @param counter only important for the hotp type */ private void saveSecretAndRefreshUserList(String user, String secret, String originalUser, OtpType type, Integer counter) { if (saveSecret(this, user, secret, originalUser, type, counter)) { refreshUserList(true); } } /** * Saves the secret key to local storage on the phone. * * @param user the user email address. When editing, the new user email. * @param secret the secret key * @param originalUser If editing, the original user email, otherwise null. * @param type hotp vs totp * @param counter only important for the hotp type * * @return {@code true} if the secret was saved, {@code false} otherwise. */ static boolean saveSecret(Context context, String user, String secret, String originalUser, OtpType type, Integer counter) { if (originalUser == null) { // new user account originalUser = user; } if (secret != null) { AccountDb accountDb = DependencyInjector.getAccountDb(); accountDb.update(user, secret, originalUser, type, counter); DependencyInjector.getOptionalFeatures().onAuthenticatorActivityAccountSaved(context, user); // TODO: Consider having a display message that activities can call and it // will present a toast with a uniform duration, and perhaps update // status messages (presuming we have a way to remove them after they // are stale). Toast.makeText(context, R.string.secret_saved, Toast.LENGTH_LONG).show(); ((Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE)) .vibrate(VIBRATE_DURATION); return true; } else { Log.e(LOCAL_TAG, "Trying to save an empty secret key"); Toast.makeText(context, R.string.error_empty_secret, Toast.LENGTH_LONG).show(); return false; } } /** Converts user list ordinal id to user email */ private String idToEmail(long id) { return mUsers[(int) id].user; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; String user = idToEmail(info.id); OtpType type = mAccountDb.getType(user); menu.setHeaderTitle(user); menu.add(0, COPY_TO_CLIPBOARD_ID, 0, R.string.copy_to_clipboard); // Option to display the check-code is only available for HOTP accounts. if (type == OtpType.HOTP) { menu.add(0, CHECK_KEY_VALUE_ID, 0, R.string.check_code_menu_item); } menu.add(0, RENAME_ID, 0, R.string.rename); menu.add(0, REMOVE_ID, 0, R.string.context_menu_remove_account); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); Intent intent; final String user = idToEmail(info.id); // final so listener can see value switch (item.getItemId()) { case COPY_TO_CLIPBOARD_ID: ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setText(mUsers[(int) info.id].pin); return true; case CHECK_KEY_VALUE_ID: intent = new Intent(Intent.ACTION_VIEW); intent.setClass(this, CheckCodeActivity.class); intent.putExtra("user", user); startActivity(intent); return true; case RENAME_ID: final Context context = this; // final so listener can see value final View frame = getLayoutInflater().inflate(R.layout.rename, (ViewGroup) findViewById(R.id.rename_root)); final EditText nameEdit = (EditText) frame.findViewById(R.id.rename_edittext); nameEdit.setText(user); new AlertDialog.Builder(this) .setTitle(String.format(getString(R.string.rename_message), user)) .setView(frame) .setPositiveButton(R.string.submit, this.getRenameClickListener(context, user, nameEdit)) .setNegativeButton(R.string.cancel, null) .show(); return true; case REMOVE_ID: // Use a WebView to display the prompt because it contains non-trivial markup, such as list View promptContentView = getLayoutInflater().inflate(R.layout.remove_account_prompt, null, false); WebView webView = (WebView) promptContentView.findViewById(R.id.web_view); webView.setBackgroundColor(Color.TRANSPARENT); // Make the WebView use the same font size as for the mEnterPinPrompt field double pixelsPerDip = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics()) / 10d; webView.getSettings().setDefaultFontSize( (int) (mEnterPinPrompt.getTextSize() / pixelsPerDip)); Utilities.setWebViewHtml( webView, "<html><body style=\"background-color: transparent;\" text=\"white\">" + getString( mAccountDb.isGoogleAccount(user) ? R.string.remove_google_account_dialog_message : R.string.remove_account_dialog_message) + "</body></html>"); new AlertDialog.Builder(this) .setTitle(getString(R.string.remove_account_dialog_title, user)) .setView(promptContentView) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.remove_account_dialog_button_remove, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { mAccountDb.delete(user); refreshUserList(true); } } ) .setNegativeButton(R.string.cancel, null) .show(); return true; default: return super.onContextItemSelected(item); } } private DialogInterface.OnClickListener getRenameClickListener(final Context context, final String user, final EditText nameEdit) { return new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { String newName = nameEdit.getText().toString(); if (newName != user) { if (mAccountDb.nameExists(newName)) { Toast.makeText(context, R.string.error_exists, Toast.LENGTH_LONG).show(); } else { saveSecretAndRefreshUserList(newName, mAccountDb.getSecret(user), user, mAccountDb.getType(user), mAccountDb.getCounter(user)); } } } }; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case R.id.add_account: addAccount(); return true; case R.id.how_it_works: displayHowItWorksInstructions(); return true; case R.id.settings: showSettings(); return true; } return super.onMenuItemSelected(featureId, item); } @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { Log.i(getString(R.string.app_name), LOCAL_TAG + ": onActivityResult"); if (requestCode == SCAN_REQUEST && resultCode == Activity.RESULT_OK) { // Grab the scan results and convert it into a URI String scanResult = (intent != null) ? intent.getStringExtra("SCAN_RESULT") : null; Uri uri = (scanResult != null) ? Uri.parse(scanResult) : null; interpretScanResult(uri, false); } } private void displayHowItWorksInstructions() { startActivity(new Intent(this, IntroEnterPasswordActivity.class)); } private void addAccount() { DependencyInjector.getOptionalFeatures().onAuthenticatorActivityAddAccount(this); } private void scanBarcode() { Intent intentScan = new Intent("com.google.zxing.client.android.SCAN"); intentScan.putExtra("SCAN_MODE", "QR_CODE_MODE"); intentScan.putExtra("SAVE_HISTORY", false); try { startActivityForResult(intentScan, SCAN_REQUEST); } catch (ActivityNotFoundException error) { showDialog(Utilities.DOWNLOAD_DIALOG); } } public static Intent getLaunchIntentActionScanBarcode(Context context) { return new Intent(AuthenticatorActivity.ACTION_SCAN_BARCODE) .setComponent(new ComponentName(context, AuthenticatorActivity.class)); } private void showSettings() { Intent intent = new Intent(); intent.setClass(this, SettingsActivity.class); startActivity(intent); } /** * Interprets the QR code that was scanned by the user. Decides whether to * launch the key provisioning sequence or the OTP seed setting sequence. * * @param scanResult a URI holding the contents of the QR scan result * @param confirmBeforeSave a boolean to indicate if the user should be * prompted for confirmation before updating the otp * account information. */ private void interpretScanResult(Uri scanResult, boolean confirmBeforeSave) { if (DependencyInjector.getOptionalFeatures().interpretScanResult(this, scanResult)) { // Scan result consumed by an optional component return; } // The scan result is expected to be a URL that adds an account. // If confirmBeforeSave is true, the user has to confirm/reject the action. // We need to ensure that new results are accepted only if the previous ones have been // confirmed/rejected by the user. This is to prevent the attacker from sending multiple results // in sequence to confuse/DoS the user. if (confirmBeforeSave) { if (mSaveKeyIntentConfirmationInProgress) { Log.w(LOCAL_TAG, "Ignoring save key Intent: previous Intent not yet confirmed by user"); return; } // No matter what happens below, we'll show a prompt which, once dismissed, will reset the // flag below. mSaveKeyIntentConfirmationInProgress = true; } // Sanity check if (scanResult == null) { showDialog(Utilities.INVALID_QR_CODE); return; } // See if the URL is an account setup URL containing a shared secret if (OTP_SCHEME.equals(scanResult.getScheme()) && scanResult.getAuthority() != null) { parseSecret(scanResult, confirmBeforeSave); } else { showDialog(Utilities.INVALID_QR_CODE); } } /** * This method is deprecated in SDK level 8, but we have to use it because the * new method, which replaces this one, does not exist before SDK level 8 */ @Override protected Dialog onCreateDialog(final int id) { Dialog dialog = null; switch(id) { /** * Prompt to download ZXing from Market. If Market app is not installed, * such as on a development phone, open the HTTPS URI for the ZXing apk. */ case Utilities.DOWNLOAD_DIALOG: AlertDialog.Builder dlBuilder = new AlertDialog.Builder(this); dlBuilder.setTitle(R.string.install_dialog_title); dlBuilder.setMessage(R.string.install_dialog_message); dlBuilder.setIcon(android.R.drawable.ic_dialog_alert); dlBuilder.setPositiveButton(R.string.install_button, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Utilities.ZXING_MARKET)); try { startActivity(intent); } catch (ActivityNotFoundException e) { // if no Market app intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Utilities.ZXING_DIRECT)); startActivity(intent); } } } ); dlBuilder.setNegativeButton(R.string.cancel, null); dialog = dlBuilder.create(); break; case DIALOG_ID_SAVE_KEY: final SaveKeyDialogParams saveKeyDialogParams = mSaveKeyDialogParams; dialog = new AlertDialog.Builder(this) .setTitle(R.string.save_key_message) .setMessage(saveKeyDialogParams.user) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { saveSecretAndRefreshUserList( saveKeyDialogParams.user, saveKeyDialogParams.secret, null, saveKeyDialogParams.type, saveKeyDialogParams.counter); } }) .setNegativeButton(R.string.cancel, null) .create(); // Ensure that whenever this dialog is to be displayed via showDialog, it displays the // correct (latest) user/account name. If this dialog is not explicitly removed after it's // been dismissed, then next time showDialog is invoked, onCreateDialog will not be invoked // and the dialog will display the previous user/account name instead of the current one. dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { removeDialog(id); onSaveKeyIntentConfirmationPromptDismissed(); } }); break; case Utilities.INVALID_QR_CODE: dialog = createOkAlertDialog(R.string.error_title, R.string.error_qr, android.R.drawable.ic_dialog_alert); markDialogAsResultOfSaveKeyIntent(dialog); break; case Utilities.INVALID_SECRET_IN_QR_CODE: dialog = createOkAlertDialog( R.string.error_title, R.string.error_uri, android.R.drawable.ic_dialog_alert); markDialogAsResultOfSaveKeyIntent(dialog); break; case DIALOG_ID_UNINSTALL_OLD_APP: dialog = new AlertDialog.Builder(this) .setTitle(R.string.dataimport_import_succeeded_uninstall_dialog_title) .setMessage( DependencyInjector.getOptionalFeatures().appendDataImportLearnMoreLink( this, getString(R.string.dataimport_import_succeeded_uninstall_dialog_prompt))) .setCancelable(true) .setPositiveButton( R.string.button_uninstall_old_app, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { startActivity(mOldAppUninstallIntent); } }) .setNegativeButton(R.string.cancel, null) .create(); break; default: dialog = DependencyInjector.getOptionalFeatures().onAuthenticatorActivityCreateDialog(this, id); if (dialog == null) { dialog = super.onCreateDialog(id); } break; } return dialog; } private void markDialogAsResultOfSaveKeyIntent(Dialog dialog) { dialog.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { onSaveKeyIntentConfirmationPromptDismissed(); } }); } /** * Invoked when a user-visible confirmation prompt for the Intent to add a new account has been * dimissed. */ private void onSaveKeyIntentConfirmationPromptDismissed() { mSaveKeyIntentConfirmationInProgress = false; } /** * Create dialog with supplied ids; icon is not set if iconId is 0. */ private Dialog createOkAlertDialog(int titleId, int messageId, int iconId) { return new AlertDialog.Builder(this) .setTitle(titleId) .setMessage(messageId) .setIcon(iconId) .setPositiveButton(R.string.ok, null) .create(); } /** * A tuple of user, OTP value, and type, that represents a particular user. * * @author adhintz@google.com (Drew Hintz) */ private static class PinInfo { private String pin; // calculated OTP, or a placeholder if not calculated private String user; private boolean isHotp = false; // used to see if button needs to be displayed /** HOTP only: Whether code generation is allowed for this account. */ private boolean hotpCodeGenerationAllowed; } /** Scale to use for the text displaying the PIN numbers. */ private static final float PIN_TEXT_SCALEX_NORMAL = 1.0f; /** Underscores are shown slightly smaller. */ private static final float PIN_TEXT_SCALEX_UNDERSCORE = 0.87f; /** * Listener for the Button that generates the next OTP value. * * @author adhintz@google.com (Drew Hintz) */ private class NextOtpButtonListener implements OnClickListener { private final Handler mHandler = new Handler(); private final PinInfo mAccount; private NextOtpButtonListener(PinInfo account) { mAccount = account; } @Override public void onClick(View v) { int position = findAccountPositionInList(); if (position == -1) { throw new RuntimeException("Account not in list: " + mAccount); } try { computeAndDisplayPin(mAccount.user, position, true); } catch (OtpSourceException e) { DependencyInjector.getOptionalFeatures().onAuthenticatorActivityGetNextOtpFailed( AuthenticatorActivity.this, mAccount.user, e); return; } final String pin = mAccount.pin; // Temporarily disable code generation for this account mAccount.hotpCodeGenerationAllowed = false; mUserAdapter.notifyDataSetChanged(); // The delayed operation below will be invoked once code generation is yet again allowed for // this account. The delay is in wall clock time (monotonically increasing) and is thus not // susceptible to system time jumps. mHandler.postDelayed( new Runnable() { @Override public void run() { mAccount.hotpCodeGenerationAllowed = true; mUserAdapter.notifyDataSetChanged(); } }, HOTP_MIN_TIME_INTERVAL_BETWEEN_CODES); // The delayed operation below will hide this OTP to prevent the user from seeing this OTP // long after it's been generated (and thus hopefully used). mHandler.postDelayed( new Runnable() { @Override public void run() { if (!pin.equals(mAccount.pin)) { return; } mAccount.pin = getString(R.string.empty_pin); mUserAdapter.notifyDataSetChanged(); } }, HOTP_DISPLAY_TIMEOUT); } /** * Gets the position in the account list of the account this listener is associated with. * * @return {@code 0}-based position or {@code -1} if the account is not in the list. */ private int findAccountPositionInList() { for (int i = 0, len = mUsers.length; i < len; i++) { if (mUsers[i] == mAccount) { return i; } } return -1; } } /** * Displays the list of users and the current OTP values. * * @author adhintz@google.com (Drew Hintz) */ private class PinListAdapter extends ArrayAdapter<PinInfo> { public PinListAdapter(Context context, int userRowId, PinInfo[] items) { super(context, userRowId, items); } /** * Displays the user and OTP for the specified position. For HOTP, displays * the button for generating the next OTP value; for TOTP, displays the countdown indicator. */ @Override public View getView(int position, View convertView, ViewGroup parent){ LayoutInflater inflater = getLayoutInflater(); PinInfo currentPin = getItem(position); View row; if (convertView != null) { // Reuse an existing view row = convertView; } else { // Create a new view row = inflater.inflate(R.layout.user_row, null); } TextView pinView = (TextView) row.findViewById(R.id.pin_value); TextView userView = (TextView) row.findViewById(R.id.current_user); View buttonView = row.findViewById(R.id.next_otp); CountdownIndicator countdownIndicator = (CountdownIndicator) row.findViewById(R.id.countdown_icon); if (currentPin.isHotp) { buttonView.setVisibility(View.VISIBLE); buttonView.setEnabled(currentPin.hotpCodeGenerationAllowed); ((ViewGroup) row).setDescendantFocusability( ViewGroup.FOCUS_BLOCK_DESCENDANTS); // makes long press work NextOtpButtonListener clickListener = new NextOtpButtonListener(currentPin); buttonView.setOnClickListener(clickListener); row.setTag(clickListener); countdownIndicator.setVisibility(View.GONE); } else { // TOTP, so no button needed buttonView.setVisibility(View.GONE); buttonView.setOnClickListener(null); row.setTag(null); countdownIndicator.setVisibility(View.VISIBLE); countdownIndicator.setPhase(mTotpCountdownPhase); } if (getString(R.string.empty_pin).equals(currentPin.pin)) { pinView.setTextScaleX(PIN_TEXT_SCALEX_UNDERSCORE); // smaller gap between underscores } else { pinView.setTextScaleX(PIN_TEXT_SCALEX_NORMAL); } pinView.setText(currentPin.pin); userView.setText(currentPin.user); return row; } } private void importDataFromOldAppIfNecessary() { if (mDataImportInProgress) { return; } mDataImportInProgress = true; DependencyInjector.getDataImportController().start(this, new ImportController.Listener() { @Override public void onOldAppUninstallSuggested(Intent uninstallIntent) { if (isFinishing()) { return; } mOldAppUninstallIntent = uninstallIntent; showDialog(DIALOG_ID_UNINSTALL_OLD_APP); } @Override public void onDataImported() { if (isFinishing()) { return; } refreshUserList(true); DependencyInjector.getOptionalFeatures().onDataImportedFromOldApp( AuthenticatorActivity.this); } @Override public void onFinished() { if (isFinishing()) { return; } mDataImportInProgress = false; } }); } /** * Parameters to the {@link AuthenticatorActivity#DIALOG_ID_SAVE_KEY} dialog. */ private static class SaveKeyDialogParams implements Serializable { private final String user; private final String secret; private final OtpType type; private final Integer counter; private SaveKeyDialogParams(String user, String secret, OtpType type, Integer counter) { this.user = user; this.secret = secret; this.type = type; this.counter = counter; } } }
zzhyjun-
src/com/google/android/apps/authenticator/AuthenticatorActivity.java
Java
asf20
44,301
/* * Copyright 2009 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.authenticator; import com.google.android.apps.authenticator.AccountDb.OtpType; import com.google.android.apps.authenticator.Base32String.DecodingException; import com.google.android.apps.authenticator.wizard.WizardPageActivity; import com.google.android.apps.authenticator2.R; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import java.io.Serializable; /** * The activity that lets the user manually add an account by entering its name, key, and type * (TOTP/HOTP). * * @author sweis@google.com (Steve Weis) */ public class EnterKeyActivity extends WizardPageActivity<Serializable> implements TextWatcher { private static final int MIN_KEY_BYTES = 10; private EditText mKeyEntryField; private EditText mAccountName; private Spinner mType; /** * Called when the activity is first created */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setPageContentView(R.layout.enter_key); // Find all the views on the page mKeyEntryField = (EditText) findViewById(R.id.key_value); mAccountName = (EditText) findViewById(R.id.account_name); mType = (Spinner) findViewById(R.id.type_choice); ArrayAdapter<CharSequence> types = ArrayAdapter.createFromResource(this, R.array.type, android.R.layout.simple_spinner_item); types.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mType.setAdapter(types); // Set listeners mKeyEntryField.addTextChangedListener(this); mRightButton.setText(R.string.enter_key_page_add_button); } /* * Return key entered by user, replacing visually similar characters 1 and 0. */ private String getEnteredKey() { String enteredKey = mKeyEntryField.getText().toString(); return enteredKey.replace('1', 'I').replace('0', 'O'); } /* * Verify that the input field contains a valid base32 string, * and meets minimum key requirements. */ private boolean validateKeyAndUpdateStatus(boolean submitting) { String userEnteredKey = getEnteredKey(); try { byte[] decoded = Base32String.decode(userEnteredKey); if (decoded.length < MIN_KEY_BYTES) { // If the user is trying to submit a key that's too short, then // display a message saying it's too short. mKeyEntryField.setError(submitting ? getString(R.string.enter_key_too_short) : null); return false; } else { mKeyEntryField.setError(null); return true; } } catch (DecodingException e) { mKeyEntryField.setError(getString(R.string.enter_key_illegal_char)); return false; } } @Override protected void onRightButtonPressed() { // TODO(cemp): This depends on the OtpType enumeration to correspond // to array indices for the dropdown with different OTP modes. OtpType mode = mType.getSelectedItemPosition() == OtpType.TOTP.value ? OtpType.TOTP : OtpType.HOTP; if (validateKeyAndUpdateStatus(true)) { AuthenticatorActivity.saveSecret(this, mAccountName.getText().toString(), getEnteredKey(), null, mode, AccountDb.DEFAULT_HOTP_COUNTER); exitWizard(); } } /** * {@inheritDoc} */ @Override public void afterTextChanged(Editable userEnteredValue) { validateKeyAndUpdateStatus(false); } /** * {@inheritDoc} */ @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // Do nothing } /** * {@inheritDoc} */ @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // Do nothing } }
zzhyjun-
src/com/google/android/apps/authenticator/EnterKeyActivity.java
Java
asf20
4,465
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.authenticator.dataexport; import android.os.Bundle; interface IExportServiceV2 { Bundle getData(); void onImportSucceeded(); }
zzhyjun-
src/com/google/android/apps/authenticator/dataexport/IExportServiceV2.aidl
AIDL
asf20
782
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.authenticator; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; /** * {@link OptionalFeatures} implementation used in Market builds. * * @author klyubin@google.com (Alex Klyubin) */ public class MarketBuildOptionalFeatures implements OptionalFeatures { @Override public void onAuthenticatorActivityCreated(AuthenticatorActivity activity) {} @Override public void onAuthenticatorActivityAccountSaved(Context context, String account) {} @Override public boolean interpretScanResult(Context context, Uri scanResult) { return false; } @Override public void onDataImportedFromOldApp(Context context) {} @Override public SharedPreferences getSharedPreferencesForDataImportFromOldApp(Context context) { return null; } @Override public String appendDataImportLearnMoreLink(Context context, String text) { return text; } @Override public OtpSource createOtpSource(AccountDb accountDb, TotpClock totpClock) { return new OtpProvider(accountDb, totpClock); } @Override public void onAuthenticatorActivityGetNextOtpFailed( AuthenticatorActivity activity, String accountName, OtpSourceException exception) { throw new RuntimeException("Failed to generate OTP for account", exception); } @Override public Dialog onAuthenticatorActivityCreateDialog(AuthenticatorActivity activity, int id) { return null; } @Override public void onAuthenticatorActivityAddAccount(AuthenticatorActivity activity) { activity.startActivity(new Intent(activity, AddOtherAccountActivity.class)); } }
zzhyjun-
src/com/google/android/apps/authenticator/MarketBuildOptionalFeatures.java
Java
asf20
2,321
/* * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.authenticator; /** * Hexadecimal encoding where each byte is represented by two hexadecimal digits. * * @author klyubin@google.com (Alex Klyubin) */ public class HexEncoding { /** Hidden constructor to prevent instantiation. */ private HexEncoding() {} private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray(); /** * Encodes the provided data as a hexadecimal string. */ public static String encode(byte[] data) { StringBuilder result = new StringBuilder(data.length * 2); for (byte b : data) { result.append(HEX_DIGITS[(b >>> 4) & 0x0f]); result.append(HEX_DIGITS[b & 0x0f]); } return result.toString(); } /** * Decodes the provided hexadecimal string into an array of bytes. */ public static byte[] decode(String encoded) { // IMPLEMENTATION NOTE: Special care is taken to permit odd number of hexadecimal digits. int resultLengthBytes = (encoded.length() + 1) / 2; byte[] result = new byte[resultLengthBytes]; int resultOffset = 0; int encodedCharOffset = 0; if ((encoded.length() % 2) != 0) { // Odd number of digits -- the first digit is the lower 4 bits of the first result byte. result[resultOffset++] = (byte) getHexadecimalDigitValue(encoded.charAt(encodedCharOffset)); encodedCharOffset++; } for (int len = encoded.length(); encodedCharOffset < len; encodedCharOffset += 2) { result[resultOffset++] = (byte) ((getHexadecimalDigitValue(encoded.charAt(encodedCharOffset)) << 4) | getHexadecimalDigitValue(encoded.charAt(encodedCharOffset + 1))); } return result; } private static int getHexadecimalDigitValue(char c) { if ((c >= 'a') && (c <= 'f')) { return (c - 'a') + 0x0a; } else if ((c >= 'A') && (c <= 'F')) { return (c - 'A') + 0x0a; } else if ((c >= '0') && (c <= '9')) { return c - '0'; } else { throw new IllegalArgumentException( "Invalid hexadecimal digit at position : '" + c + "' (0x" + Integer.toHexString(c) + ")"); } } }
zzhyjun-
src/com/google/android/apps/authenticator/HexEncoding.java
Java
asf20
2,721
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.authenticator.dataimport; import android.content.Context; import android.content.Intent; /** * Controller for importing data from the "old" app. * * @author klyubin@google.com (Alex Klyubin) */ public interface ImportController { public interface Listener { void onDataImported(); void onOldAppUninstallSuggested(Intent uninstallIntent); void onFinished(); } void start(Context context, Listener listener); }
zzhyjun-
src/com/google/android/apps/authenticator/dataimport/ImportController.java
Java
asf20
1,083
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.authenticator.dataimport; import com.google.android.apps.authenticator.AccountDb; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Imports the contents of {@link AccountDb} and the key material and settings from a * {@link Bundle}. * * @author klyubin@google.com (Alex Klyubin) */ public class Importer { private static final String LOG_TAG = Importer.class.getSimpleName(); // @VisibleForTesting static final String KEY_ACCOUNTS = "accountDb"; // @VisibleForTesting static final String KEY_PREFERENCES = "preferences"; // @VisibleForTesting static final String KEY_NAME = "name"; // @VisibleForTesting static final String KEY_ENCODED_SECRET = "encodedSecret"; // @VisibleForTesting static final String KEY_TYPE = "type"; // @VisibleForTesting static final String KEY_COUNTER = "counter"; /** * Imports the contents of the provided {@link Bundle} into the provided {@link AccountDb} and * {@link SharedPreferences}. Does not overwrite existing records in the database. * * @param bundle source bundle. * @param accountDb destination {@link AccountDb}. * @param preferences destination preferences or {@code null} for none. */ public void importFromBundle(Bundle bundle, AccountDb accountDb, SharedPreferences preferences) { Bundle accountDbBundle = bundle.getBundle(KEY_ACCOUNTS); if (accountDbBundle != null) { importAccountDbFromBundle(accountDbBundle, accountDb); } if (preferences != null) { Bundle preferencesBundle = bundle.getBundle(KEY_PREFERENCES); if (preferencesBundle != null) { importPreferencesFromBundle(preferencesBundle, preferences); } } } private void importAccountDbFromBundle(Bundle bundle, AccountDb accountDb) { // Each account is stored in a Bundle whose key is a string representing the ordinal (integer) // position of the account in the database. List<String> sortedAccountBundleKeys = new ArrayList<String>(bundle.keySet()); Collections.sort(sortedAccountBundleKeys, new IntegerStringComparator()); int importedAccountCount = 0; for (String accountBundleKey : sortedAccountBundleKeys) { Bundle accountBundle = bundle.getBundle(accountBundleKey); String name = accountBundle.getString(KEY_NAME); if (name == null) { Log.w(LOG_TAG, "Skipping account #" + accountBundleKey + ": name missing"); continue; } if (accountDb.nameExists(name)) { // Don't log account name here and below because it's considered PII Log.w(LOG_TAG, "Skipping account #" + accountBundleKey + ": already configured"); continue; } String encodedSecret = accountBundle.getString(KEY_ENCODED_SECRET); if (encodedSecret == null) { Log.w(LOG_TAG, "Skipping account #" + accountBundleKey + ": secret missing"); continue; } String typeString = accountBundle.getString(KEY_TYPE); AccountDb.OtpType type; if ("totp".equals(typeString)) { type = AccountDb.OtpType.TOTP; } else if ("hotp".equals(typeString)) { type = AccountDb.OtpType.HOTP; } else { Log.w(LOG_TAG, "Skipping account #" + accountBundleKey + ": unsupported type: \"" + typeString + "\""); continue; } Integer counter = accountBundle.containsKey(KEY_COUNTER) ? accountBundle.getInt(KEY_COUNTER) : null; if (counter == null) { if (type == AccountDb.OtpType.HOTP) { Log.w(LOG_TAG, "Skipping account #" + accountBundleKey + ": counter missing"); continue; } else { // TOTP counter = AccountDb.DEFAULT_HOTP_COUNTER; } } accountDb.update(name, encodedSecret, name, type, counter); importedAccountCount++; } Log.i(LOG_TAG, "Imported " + importedAccountCount + " accounts"); } private static class IntegerStringComparator implements Comparator<String> { @Override public int compare(String lhs, String rhs) { int lhsValue = Integer.parseInt(lhs); int rhsValue = Integer.parseInt(rhs); return lhsValue - rhsValue; } } private boolean tryImportPreferencesFromBundle(Bundle bundle, SharedPreferences preferences) { SharedPreferences.Editor preferencesEditor = preferences.edit(); for (String key : bundle.keySet()) { Object value = bundle.get(key); if (value instanceof Boolean) { preferencesEditor.putBoolean(key, (Boolean) value); } else if (value instanceof Float) { preferencesEditor.putFloat(key, (Float) value); } else if (value instanceof Integer) { preferencesEditor.putInt(key, (Integer) value); } else if (value instanceof Long) { preferencesEditor.putLong(key, (Long) value); } else if (value instanceof String) { preferencesEditor.putString(key, (String) value); } else { // Ignore: can only be Set<String> at the moment (API Level 11+), which we don't use anyway. } } return preferencesEditor.commit(); } private void importPreferencesFromBundle(Bundle bundle, SharedPreferences preferences) { // Retry until the operation succeeds while (!tryImportPreferencesFromBundle(bundle, preferences)) {} } }
zzhyjun-
src/com/google/android/apps/authenticator/dataimport/Importer.java
Java
asf20
6,086
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.authenticator.dataimport; import com.google.android.apps.authenticator.dataexport.IExportServiceV2; import com.google.android.apps.authenticator.testability.DependencyInjector; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; /** * @author klyubin@google.com (Alex Klyubin) */ public class ExportServiceBasedImportController implements ImportController { private static final String OLD_APP_PACKAGE_NAME = "com.google.android.apps.authenticator"; private static final String OLD_APP_EXPORT_SERVICE_CLASS_NAME = OLD_APP_PACKAGE_NAME + ".dataexport.ExportServiceV2"; private static final String LOG_TAG = "ImportController"; public ExportServiceBasedImportController() {} @Override public void start(Context context, Listener listener) { int oldAppVersionCode = getOldAppVersionCode(); if (oldAppVersionCode == -1) { Log.d(LOG_TAG, "Skipping importing because the old app is not installed"); notifyListenerFinished(listener); return; } Intent intent = new Intent(); intent.setComponent(new ComponentName(OLD_APP_PACKAGE_NAME, OLD_APP_EXPORT_SERVICE_CLASS_NAME)); ServiceConnection serviceConnection = new ExportServiceConnection(context, listener); boolean bound = context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); if (!bound) { Log.i(LOG_TAG, "Not importing because the old app is too old (" + oldAppVersionCode + ") and can't export"); context.unbindService(serviceConnection); notifyListenerFinished(listener); return; } // The flow continues in ExportServiceConnection.onServiceConnected which is invoked // later on by the OS once the connection with the ExportService has been established. } private class ExportServiceConnection implements ServiceConnection { private final Context mContext; private final Listener mListener; private ExportServiceConnection(Context context, Listener listener) { mContext = context; mListener = listener; } @Override public void onServiceConnected(ComponentName name, IBinder service) { try { IExportServiceV2 exportService; try { exportService = IExportServiceV2.Stub.asInterface(service); } catch (SecurityException e) { Log.w(LOG_TAG, "Failed to obtain export interface: " + e); return; } Bundle importedData; try { importedData = exportService.getData(); } catch (SecurityException e) { Log.w(LOG_TAG, "Failed to obtain data: " + e); return; } catch (RemoteException e) { Log.w(LOG_TAG, "Failed to obtain data: " + e); return; } if (importedData != null) { new Importer().importFromBundle( importedData, DependencyInjector.getAccountDb(), DependencyInjector.getOptionalFeatures() .getSharedPreferencesForDataImportFromOldApp(mContext)); Log.i(LOG_TAG, "Successfully imported data from the old app"); notifyListenerDataImported(mListener); try { exportService.onImportSucceeded(); } catch (SecurityException e) { Log.w(LOG_TAG, "Failed to notify old app that import succeeded: " + e); return; } catch (RemoteException e) { Log.w(LOG_TAG, "Failed to notify old app that import succeeded: " + e); return; } notifyListenerUninstallOldAppSuggested(mListener); } else { Log.w(LOG_TAG, "Old app returned null data"); } } finally { // The try-catch below is to avoid crashing when the unbind operation fails. Occasionally // the operation throws an IllegalArgumentException because the connection has been closed // by the OS/framework. try { mContext.unbindService(this); } catch (Exception e) { Log.w(LOG_TAG, "Failed to unbind service", e); } finally { notifyListenerFinished(mListener); } } } @Override public void onServiceDisconnected(ComponentName name) {} } /** * Gets the version code of the old app. * * @return version code or {@code -1} if the old app is not installed. */ private static int getOldAppVersionCode() { try { PackageInfo oldAppPackageInfo = DependencyInjector.getPackageManager().getPackageInfo( OLD_APP_PACKAGE_NAME, 0); return oldAppPackageInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { return -1; } } private static void notifyListenerDataImported(Listener listener) { if (listener != null) { listener.onDataImported(); } } private static void notifyListenerUninstallOldAppSuggested(Listener listener) { if (listener != null) { listener.onOldAppUninstallSuggested( new Intent(Intent.ACTION_DELETE, Uri.parse("package:" + OLD_APP_PACKAGE_NAME))); } } private static void notifyListenerFinished(Listener listener) { if (listener != null) { listener.onFinished(); } } }
zzhyjun-
src/com/google/android/apps/authenticator/dataimport/ExportServiceBasedImportController.java
Java
asf20
6,138
/* * Copyright 2010 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.authenticator; import android.webkit.WebView; /** * A class for handling a variety of utility things. This was mostly made * because I needed to centralize dialog related constants. I foresee this class * being used for other code sharing across Activities in the future, however. * * @author alexei@czeskis.com (Alexei Czeskis) * */ public class Utilities { // Links public static final String ZXING_MARKET = "market://search?q=pname:com.google.zxing.client.android"; public static final String ZXING_DIRECT = "https://zxing.googlecode.com/files/BarcodeScanner3.1.apk"; // Dialog IDs public static final int DOWNLOAD_DIALOG = 0; public static final int MULTIPLE_ACCOUNTS_DIALOG = 1; static final int INVALID_QR_CODE = 3; static final int INVALID_SECRET_IN_QR_CODE = 7; public static final long SECOND_IN_MILLIS = 1000; public static final long MINUTE_IN_MILLIS = 60 * SECOND_IN_MILLIS; // Constructor -- Does nothing yet private Utilities() { } public static final long millisToSeconds(long timeMillis) { return timeMillis / 1000; } public static final long secondsToMillis(long timeSeconds) { return timeSeconds * 1000; } /** * Sets the provided HTML as the contents of the provided {@link WebView}. */ public static void setWebViewHtml(WebView view, String html) { view.loadDataWithBaseURL(null, html, "text/html", "utf-8", null); } }
zzhyjun-
src/com/google/android/apps/authenticator/Utilities.java
Java
asf20
2,067
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Tasks.ASP.NET.SimpleOAuth2")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Tasks.ASP.NET.SimpleOAuth2")] [assembly: AssemblyCopyright("Copyright © Microsoft 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3eab9992-044c-4242-a089-7c5df8dcac76")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
Tasks.ASP.NET.SimpleOAuth2/Properties/AssemblyInfo.cs
C#
asf20
1,441
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Drawing; using System.Linq; using System.Threading; using System.Web; using System.Web.UI.WebControls; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication.OAuth2; using Google.Apis.Services; using Google.Apis.Samples.Helper; using Google.Apis.Tasks.v1; using Google.Apis.Tasks.v1.Data; using Google.Apis.Util; namespace Tasks.ASP.NET.SimpleOAuth2 { /// <summary> /// This sample uses the Tasks service and OAuth2 authentication /// to list all of your tasklists and tasks. /// </summary> public partial class _Default : System.Web.UI.Page { private static TasksService _service; // We don't need individual service instances for each client. private static OAuth2Authenticator<WebServerClient> _authenticator; private IAuthorizationState _state; /// <summary> /// Returns the authorization state which was either cached or set for this session. /// </summary> private IAuthorizationState AuthState { get { return _state ?? HttpContext.Current.Session["AUTH_STATE"] as IAuthorizationState; } } protected void Page_Load(object sender, EventArgs e) { // Create the Tasks-Service if it is null. if (_service == null) { _authenticator = CreateAuthenticator(); _service = new TasksService(new BaseClientService.Initializer() { Authenticator = _authenticator, ApplicationName = "Tasks API Sample", }); } // Check if we received OAuth2 credentials with this request; if yes: parse it. if (HttpContext.Current.Request["code"] != null) { _authenticator.LoadAccessToken(); } // Change the button depending on our auth-state. listButton.Text = AuthState == null ? "Authenticate" : "Fetch Tasklists"; } private OAuth2Authenticator<WebServerClient> CreateAuthenticator() { // Register the authenticator. var provider = new WebServerClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = ClientCredentials.ClientID; provider.ClientSecret = ClientCredentials.ClientSecret; var authenticator = new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization) { NoCaching = true }; return authenticator; } private IAuthorizationState GetAuthorization(WebServerClient client) { // If this user is already authenticated, then just return the auth state. IAuthorizationState state = AuthState; if (state != null) { return state; } // Check if an authorization request already is in progress. state = client.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request)); if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken))) { // Store and return the credentials. HttpContext.Current.Session["AUTH_STATE"] = _state = state; return state; } // Otherwise do a new authorization request. string scope = TasksService.Scopes.TasksReadonly.GetStringValue(); OutgoingWebResponse response = client.PrepareRequestUserAuthorization(new[] { scope }); response.Send(); // Will throw a ThreadAbortException to prevent sending another response. return null; } /// <summary> /// Gets the TasksLists of the user. /// </summary> public void FetchTaskslists() { try { // Execute all TasksLists of the user asynchronously. TaskLists response = _service.Tasklists.List().Execute(); ShowTaskslists(response); } catch (ThreadAbortException) { // User was not yet authenticated and is being forwarded to the authorization page. throw; } catch (Exception ex) { output.Text = ex.ToHtmlString(); } } private void ShowTaskslists(TaskLists response) { if (response.Items == null) // If no item is in the response, .Items will be null. { output.Text += "You have no task lists!<br/>"; return; } output.Text += "Showing task lists...<br/>"; foreach (TaskList list in response.Items) { Panel listPanel = new Panel() { BorderWidth = Unit.Pixel(1), BorderColor = Color.Black }; listPanel.Controls.Add(new Label { Text = list.Title }); listPanel.Controls.Add(new Label { Text = "<hr/>" }); listPanel.Controls.Add(new Label { Text = GetTasks(list) }); lists.Controls.Add(listPanel); } } private string GetTasks(TaskList taskList) { var tasks = _service.Tasks.List(taskList.Id).Execute(); if (tasks.Items == null) { return "<i>No items</i>"; } var query = from t in tasks.Items select t.Title; return query.Select((str) => "&bull; " + str).Aggregate((a, b) => a + "<br/>" + b); } protected void listButton_Click(object sender, EventArgs e) { FetchTaskslists(); } } }
zzfocuzz-deepbotcopy
Tasks.ASP.NET.SimpleOAuth2/Default.aspx.cs
C#
asf20
6,558
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using Google.Apis.Samples.Helper; namespace Tasks.ASP.NET.SimpleOAuth2 { /// <summary> /// This class provides the client credentials for all the samples in this solution. /// In order to run all of the samples, you have to enable API access for every API /// you want to use, enter your credentials here. /// /// You can find your credentials here: /// https://code.google.com/apis/console/#:access /// /// For your own application you should find a more secure way than just storing your client secret inside a string, /// as it can be lookup up easily using a reflection tool. /// </summary> internal static class ClientCredentials { /// <summary> /// The OAuth2.0 Client ID of your project. /// </summary> public static readonly string ClientID = "<Enter your ClientID here>"; /// <summary> /// The OAuth2.0 Client secret of your project. /// </summary> public static readonly string ClientSecret = "<Enter your ClientSecret here>"; /// <summary> /// Your Api/Developer key. /// </summary> public static readonly string ApiKey = "<Enter your ApiKey here>"; #region Verify Credentials static ClientCredentials() { ReflectionUtils.VerifyCredentials(typeof(ClientCredentials)); } #endregion } }
zzfocuzz-deepbotcopy
Tasks.ASP.NET.SimpleOAuth2/ClientCredentials.cs
C#
asf20
2,021
<%@ Page Language="C#" EnableSessionState="true" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Async="true" Inherits="Tasks.ASP.NET.SimpleOAuth2._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <h1>ASP.NET Tasks API &ndash; OAuth2 Sample</h1> <form id="mainForm" runat="server"> Click the button below to authorize this application/list all TaskLists and Tasks. <br/><br/> <div> &nbsp; &nbsp; <asp:Button ID="listButton" runat="server" Text="List Tasks!" onclick="listButton_Click" /> </div> <br/> <asp:PlaceHolder ID="lists" runat="server"></asp:PlaceHolder><br/> <asp:Label ID="output" runat="server"></asp:Label> </form> <p> <i>&copy; 2011 Google Inc</i> </p> </body> </html>
zzfocuzz-deepbotcopy
Tasks.ASP.NET.SimpleOAuth2/Default.aspx
ASP.NET
asf20
1,009
<html> <title>Google .NET Client API &ndash; Tasks.ASP.NET.SimpleOAuth2</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Tasks.ASP.NET.SimpleOAuth2</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FTasks.ASP.NET.SimpleOAuth2">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.ASP.NET.SimpleOAuth2/Default.aspx.cs?repo=samples">Default.aspx.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Tasks API for your project </li> <li>Edit <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.ASP.NET.SimpleOAuth2/ClientCredentials.cs?repo=samples">ClientCredentials.cs</a> to insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane.</li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Run the webpage using the builtin Visual Studio ASP.NET server (press F5)</li> </ul> </body> </html>
zzfocuzz-deepbotcopy
Tasks.ASP.NET.SimpleOAuth2/README.html
HTML
asf20
1,848
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Tasks.CreateTasks")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("Tasks.CreateTasks")] [assembly: AssemblyCopyright("Copyright © Google Inc 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c85adfc3-ca73-4eea-8d59-db3bf2769a44")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
Tasks.CreateTasks/Properties/AssemblyInfo.cs
C#
asf20
1,466
<html> <title>Google .NET Client API &ndash; Tasks.CreateTasks</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Tasks.CreateTasks</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FTasks.CreateTasks">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.CreateTasks/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Tasks API for your project </li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Tasks.CreateTasks\bin\Debug</i></li> <li> When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane. </li> </ul> </body> </html>
zzfocuzz-deepbotcopy
Tasks.CreateTasks/README.html
HTML
asf20
1,638
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System.Linq; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Services; using Google.Apis.Samples.Helper; using Google.Apis.Tasks.v1; using Google.Apis.Tasks.v1.Data; using Google.Apis.Util; namespace TasksSample.CreateTasks { /// <summary> /// Tasks API sample using OAuth2. /// This sample demonstrates how to use OAuth2 and how to request an access code. /// The application will only ask you to grant access to this sample once, even when run multiple times. /// </summary> internal class Program { private const string SampleListName = ".NET Tasks API Example"; private static readonly string Scope = TasksService.Scopes.Tasks.GetStringValue(); public static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Tasks API"); // Register the authenticator. FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials(); var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = credentials.ClientId, ClientSecret = credentials.ClientSecret }; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); // Create the service. var service = new TasksService(new BaseClientService.Initializer() { Authenticator = auth, ApplicationName = "Tasks API Sample", }); // Execute request: Create sample list. if (!ListExists(service, SampleListName) && CommandLine.RequestUserChoice("Do you want to create a sample list?")) { CreateSampleTasklist(service); } CommandLine.WriteLine(); // Execute request: List task-lists. ListTaskLists(service); CommandLine.PressAnyKeyToExit(); } private static IAuthorizationState GetAuthorization(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.samples.dotnet.siteverification"; const string KEY = "y},drdzf11x9;87"; // Check if there is a cached refresh token available. IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, Scope); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } private static bool ListExists(TasksService service, string list) { return (from TaskList taskList in service.Tasklists.List().Execute().Items where taskList.Title == list select taskList).Count() > 0; } private static void CreateSampleTasklist(TasksService service) { var list = new TaskList(); list.Title = SampleListName; list = service.Tasklists.Insert(list).Execute(); service.Tasks.Insert(new Task { Title = "Test the Tasklist API" }, list.Id).Execute(); service.Tasks.Insert(new Task { Title = "Do the laundry" }, list.Id).Execute(); } private static void ListTaskLists(TasksService service) { CommandLine.WriteLine(" ^1Task lists:"); var list = service.Tasklists.List().Execute(); foreach (var item in list.Items) { CommandLine.WriteLine(" ^2" + item.Title); Tasks tasks = service.Tasks.List(item.Id).Execute(); if (tasks.Items != null) { foreach (Task t in tasks.Items) { CommandLine.WriteLine(" ^4" + t.Title); } } } } } }
zzfocuzz-deepbotcopy
Tasks.CreateTasks/Program.cs
C#
asf20
5,527
<html> <title>Google .NET Client API &ndash; Plus.ServiceAccount</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Plus.ServiceAccount</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FPlus.ServiceAccount">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Plus.ServiceAccount/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Google+ API</li> <li>Replace <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Plus.ServiceAccount/key.p12?repo=samples">key.p12</a> with the private key that is generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane for your Service Account.</li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Plus.ServiceAccount\bin\Debug</i></li> </ul> </body> </html>
zzfocuzz-deepbotcopy
Plus.ServiceAccount/README.html
HTML
asf20
1,777
/* Copyright 2012 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Diagnostics; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Plus.v1; using Google.Apis.Plus.v1.Data; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Util; namespace Google.Apis.Samples.PlusServiceAccount { /// <summary> /// This sample demonstrates the simplest use case for a Service Account service. /// The certificate needs to be downloaded from the APIs Console /// <see cref="https://code.google.com/apis/console/#:access"/>: /// "Create another client ID..." -> "Service Account" -> Download the certificate as "key.p12" and replace the /// placeholder. /// The schema provided here can be applied to every request requiring authentication. /// <see cref="https://developers.google.com/accounts/docs/OAuth2#serviceaccount"/> for more information. /// </summary> public class Program { // A known public activity. private static String ACTIVITY_ID = "z12gtjhq3qn2xxl2o224exwiqruvtda0i"; public static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Plus API - Service Account"); String serviceAccountEmail = CommandLine.RequestUserInput<String>( "Service account e-mail address (from the APIs Console)"); try { X509Certificate2 certificate = new X509Certificate2( @"key.p12", "notasecret", X509KeyStorageFlags.Exportable); // service account credential (uncomment ServiceAccountUser for domain-wide delegation) var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate) { ServiceAccountId = serviceAccountEmail, Scope = PlusService.Scopes.PlusMe.GetStringValue(), // ServiceAccountUser = "user@example.com", }; var auth = new OAuth2Authenticator<AssertionFlowClient>( provider, AssertionFlowClient.GetState); // Create the service. var service = new PlusService(new BaseClientService.Initializer() { Authenticator = auth, ApplicationName = "Plus API Sample", }); Activity activity = service.Activities.Get(ACTIVITY_ID).Execute(); CommandLine.WriteLine(" ^1Activity: " + activity.Object.Content); CommandLine.WriteLine(" ^1Video: " + activity.Object.Attachments[0].Url); // Success. CommandLine.PressAnyKeyToExit(); } catch (CryptographicException) { CommandLine.WriteLine( "Unable to load certificate, please download key.p12 file from the Google " + "APIs Console at https://code.google.com/apis/console/"); CommandLine.PressAnyKeyToExit(); } } } }
zzfocuzz-deepbotcopy
Plus.ServiceAccount/Program.cs
C#
asf20
3,999
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Tasks.SimpleOAuth2")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("Tasks.SimpleOAuth2")] [assembly: AssemblyCopyright("Copyright © Google Inc 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5cd7a01f-6233-47da-8860-c515e7c05511")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
Tasks.SimpleOAuth2/Properties/AssemblyInfo.cs
C#
asf20
1,428
<html> <title>Google .NET Client API &ndash; Tasks.SimpleOAuth2</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Tasks.SimpleOAuth2</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FTasks.SimpleOAuth2">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.SimpleOAuth2/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Tasks API for your project </li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Tasks.SimpleOAuth2\bin\Debug</i></li> <li> When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane. </li> </ul> </body> </html>
zzfocuzz-deepbotcopy
Tasks.SimpleOAuth2/README.html
HTML
asf20
1,643
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Diagnostics; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Tasks.v1; using Google.Apis.Tasks.v1.Data; using Google.Apis.Util; namespace Google.Apis.Samples.TasksOAuth2 { /// <summary> /// This sample demonstrates the simplest use case for an OAuth2 service. /// The schema provided here can be applied to every request requiring authentication. /// </summary> public class Program { public static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Tasks API"); // Register the authenticator. FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials(); var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = credentials.ClientId, ClientSecret = credentials.ClientSecret }; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); // Create the service. var service = new TasksService(new BaseClientService.Initializer() { Authenticator = auth, ApplicationName = "Tasks API Sample" }); TaskLists results = service.Tasklists.List().Execute(); CommandLine.WriteLine(" ^1Lists:"); foreach (TaskList list in results.Items) { CommandLine.WriteLine(" ^2" + list.Title); } CommandLine.PressAnyKeyToExit(); } private static IAuthorizationState GetAuthorization(NativeApplicationClient arg) { // Get the auth URL: IAuthorizationState state = new AuthorizationState(new[] { TasksService.Scopes.Tasks.GetStringValue() }); state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl); Uri authUri = arg.RequestUserAuthorization(state); // Request authorization from the user (by opening a browser window): Process.Start(authUri.ToString()); Console.Write(" Authorization Code: "); string authCode = Console.ReadLine(); Console.WriteLine(); // Retrieve the access token by using the authorization code: return arg.ProcessUserAuthorization(authCode, state); } } }
zzfocuzz-deepbotcopy
Tasks.SimpleOAuth2/Program.cs
C#
asf20
3,376
/* Copyright 2012 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using DotNetOpenAuth.OAuth2; using AdSenseHost.Sample.Host; using AdSenseHost.Sample.Publisher; using Google.Apis.Adsensehost.v4_1; using Google.Apis.Adsensehost.v4_1.Data; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Util; namespace AdSenseHost.Sample { /// <summary> /// A sample application that handles sessions on the AdSense Host API. /// For more information visit the "Host API Signup Flow" guide in /// https://developers.google.com/adsense/host/signup /// <list type="bullet"> /// <item> /// <description>Starting an association session</description> /// </item> /// <item> /// <description>Verifying an association session</description> /// </item> /// </list> /// </summary> internal class AssociationSessionSample { private static readonly string Scope = AdSenseHostService.Scopes.Adsensehost.GetStringValue(); [STAThread] public static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("AdSense Host API Command Line Sample - Association sessions"); // Register the authenticator. FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials(); NativeApplicationClient provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = credentials.ClientId, ClientSecret = credentials.ClientSecret }; OAuth2Authenticator<NativeApplicationClient> auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication); // Create the service. AdSenseHostService service = new AdSenseHostService(new BaseClientService.Initializer() { Authenticator = auth, ApplicationName = "Adsense Host API Sample", }); string websiteUrl = null; CommandLine.RequestUserInput("Insert website URL", ref websiteUrl); /* 1. Create the association session. */ StartAssociationSession(service, websiteUrl); /* 2. Use the token to verify the association. */ string callbackToken = null; CommandLine.RequestUserInput("Insert callback token", ref callbackToken); VerifyAssociationSession(service, callbackToken); CommandLine.PressAnyKeyToExit(); } /// <summary> /// This example starts an association session. /// </summary> /// <param name="adsense">AdSensehost service object on which to run the requests.</param> /// <param name="websiteUrl">The URL of the user's hosted website.</param> /// <returns>The created association.</returns> public static AssociationSession StartAssociationSession(AdSenseHostService adsense, string websiteUrl) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Creating new association session"); CommandLine.WriteLine("================================================================="); // Request a new association session. AssociationSession associationSession = adsense.Associationsessions.Start( AssociationsessionsResource.ProductCode.AFC, websiteUrl).Execute(); CommandLine.WriteLine("Association with ID {0} and redirect URL \n{1}\n was started.", associationSession.Id, associationSession.RedirectUrl); CommandLine.WriteLine(); // Return the Association Session that was just created. return associationSession; } /// <summary> /// This example verifies an association session callback token. /// </summary> /// <param name="adsense">AdSensehost service object on which to run the requests.</param> /// <param name="callbackToken">The token returned from the association callback.</param> public static void VerifyAssociationSession(AdSenseHostService adsense, string callbackToken) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Verifying new association session"); CommandLine.WriteLine("================================================================="); // Verify the association session token. AssociationSession associationSession = adsense.Associationsessions.Verify(callbackToken) .Execute(); CommandLine.WriteLine("Association for account {0} has status {1} and ID {2}.", associationSession.AccountId, associationSession.Status, associationSession.Id); CommandLine.WriteLine(); } private static IAuthorizationState GetAuthentication(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.samples.dotnet.adsensehostsessions"; const string KEY = "9(R4;.nFt1Kr_y`b'[@d9(R4;.1Kr_y"; IAuthorizationState state = null; try { // Check if there is a cached refresh token available. state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); } catch (System.Security.Cryptography.CryptographicException ex) { CommandLine.WriteError("Getting Refresh token failed: " + ex.Message); CommandLine.WriteLine("Requesting new authorization..."); state = null; } if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, Scope); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } } }
zzfocuzz-deepbotcopy
AdSenseHost.Sample/AssociationSessionSample.cs
C#
asf20
7,524
/* Copyright 2012 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using Google.Apis.Adsensehost.v4_1; using Google.Apis.Adsensehost.v4_1.Data; using Google.Apis.Samples.Helper; namespace AdSenseHost.Sample.Host { /// <summary> /// A sample consumer that runs multiple Host requests against the AdSense Host API. /// These include: /// <list type="bullet"> /// <item> /// <description>Getting a list of all host ad clients</description> /// </item> /// <item> /// <description>Getting a list of all host custom channels</description> /// </item> /// <item> /// <description>Adding a new host custom channel</description> /// </item> /// <item> /// <description>Updating an existing host custom channel</description> /// </item> /// <item> /// <description>Deleting a host custom channel</description> /// </item> /// <item> /// <description>Getting a list of all host URL channels</description> /// </item> /// <item> /// <description>Adding a new host URL channel</description> /// </item> /// <item> /// <description>Deleting an existing host URL channel</description> /// </item> /// <item> /// <description>Running a report for a host ad client, for the past 7 days</description> /// </item> /// </list> /// </summary> public class HostApiConsumer { AdSenseHostService service; int maxListPageSize; private static readonly string DateFormat = "yyyy-MM-dd"; /// <summary> /// Runs multiple Host requests againt the AdSense Host API. /// </summary> /// <param name="service">AdSensehost service object on which to run the requests.</param> /// <param name="maxListPageSize">The maximum page size to retrieve.</param> public HostApiConsumer(AdSenseHostService service, int maxListPageSize) { this.service = service; this.maxListPageSize = maxListPageSize; } internal void RunCalls() { AdClients adClients = GetAllAdClients(); // Get a host ad client ID, so we can run the rest of the samples. // Make sure it's a host ad client. AdClient exampleAdClient = FindAdClientForHost(adClients.Items); if (exampleAdClient != null) { // Custom Channels: List, Add, Update, Delete CustomChannels hostCustomChannels = GetAllCustomChannels(exampleAdClient.Id); CustomChannel newCustomChannel = AddCustomChannel(exampleAdClient.Id); newCustomChannel = UpdateCustomChannel(exampleAdClient.Id, newCustomChannel.Id); DeleteCustomChannel(exampleAdClient.Id, newCustomChannel.Id); // URL Channels: List, Add, Delete GetAllUrlChannels(exampleAdClient.Id); UrlChannel newUrlChannel = AddUrlChannel(exampleAdClient.Id); DeleteUrlChannel(exampleAdClient.Id, newUrlChannel.Id); GenerateReport(service, exampleAdClient.Id); } else { CommandLine.WriteLine("No host ad clients found, unable to run remaining host samples."); } } /// <summary> /// This example gets all custom channels in an ad client. /// </summary> /// <param name="adClientId">The ID for the ad client to be used.</param> /// <returns>The last page of custom channels.</returns> private CustomChannels GetAllCustomChannels(string adClientId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all custom channels for ad client {0}", adClientId); CommandLine.WriteLine("================================================================="); // Retrieve custom channel list in pages and display data as we receive it. string pageToken = null; CustomChannels customChannelResponse = null; do { var customChannelRequest = this.service.Customchannels.List(adClientId); customChannelRequest.MaxResults = this.maxListPageSize; customChannelRequest.PageToken = pageToken; customChannelResponse = customChannelRequest.Execute(); if (customChannelResponse.Items != null && customChannelResponse.Items.Count > 0) { foreach (var customChannel in customChannelResponse.Items) { CommandLine.WriteLine("Custom channel with code \"{0}\" and name \"{1}\" was found.", customChannel.Code, customChannel.Name); } } else { CommandLine.WriteLine("No custom channels found."); } pageToken = customChannelResponse.NextPageToken; } while (pageToken != null); CommandLine.WriteLine(); // Return the last page of custom channels, so that the main sample has something to run. return customChannelResponse; } /// <summary> /// This example gets all ad clients for the logged in user's default account. /// </summary> /// <returns>The last page of ad clients.</returns> private AdClients GetAllAdClients() { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all ad clients for default account"); CommandLine.WriteLine("================================================================="); // Retrieve ad client list in pages and display data as we receive it. string pageToken = null; AdClients adClientResponse = null; do { var adClientRequest = this.service.Adclients.List(); adClientRequest.MaxResults = this.maxListPageSize; adClientRequest.PageToken = pageToken; adClientResponse = adClientRequest.Execute(); if (adClientResponse.Items != null && adClientResponse.Items.Count > 0) { foreach (var adClient in adClientResponse.Items) { CommandLine.WriteLine("Ad client for product \"{0}\" with ID \"{1}\" was found.", adClient.ProductCode, adClient.Id); CommandLine.WriteLine("\tSupports reporting: {0}", adClient.SupportsReporting.Value ? "Yes" : "No"); } } else { CommandLine.WriteLine("No ad clients found."); } pageToken = adClientResponse.NextPageToken; } while (pageToken != null); CommandLine.WriteLine(); // Return the last page of ad clients, so that the main sample has something to run. return adClientResponse; } /// <summary> /// This example adds a custom channel to a host ad client. /// </summary> /// <param name="adClientId">The ID for the ad client to be used.</param> /// <returns>The created custom channel.</returns> private CustomChannel AddCustomChannel(string adClientId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Adding custom channel to ad client {0}", adClientId); CommandLine.WriteLine("================================================================="); CustomChannel newCustomChannel = new CustomChannel(); System.Random random = new System.Random(System.DateTime.Now.Millisecond); newCustomChannel.Name = "Sample Channel #" + random.Next(0, 10000).ToString(); // Create custom channel. CustomChannel customChannel = this.service.Customchannels .Insert(newCustomChannel, adClientId).Execute(); CommandLine.WriteLine("Custom channel with id {0}, code {1} and name {2} was created", customChannel.Id, customChannel.Code, customChannel.Name); CommandLine.WriteLine(); // Return the Custom Channel that was just created return customChannel; } /// <summary> /// This example updates a custom channel on a host ad client. /// </summary> /// <param name="adClientId">The ID for the ad client to be used.</param> /// <param name="customChannelId">The ID for the custom channel to be updated.</param> /// <returns>The updated custom channel.</returns> private CustomChannel UpdateCustomChannel(string adClientId, string customChannelId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Updating custom channel {0}", customChannelId); CommandLine.WriteLine("================================================================="); CustomChannel patchCustomChannel = new CustomChannel(); System.Random random = new System.Random(System.DateTime.Now.Millisecond); patchCustomChannel.Name = "Updated Sample Channel #" + random.Next(0, 10000).ToString(); // Update custom channel: Using REST's PATCH method to update just the Name field. CustomChannel customChannel = this.service.Customchannels .Patch(patchCustomChannel, adClientId, customChannelId).Execute(); CommandLine.WriteLine("Custom channel with id {0}, code {1} and name {2} was updated", customChannel.Id, customChannel.Code, customChannel.Name); CommandLine.WriteLine(); // Return the Custom Channel that was just created return customChannel; } /// <summary> /// This example deletes a custom channel on a host ad client. /// </summary> /// <param name="adClientId">The ID for the ad client to be used.</param> /// <param name="customChannelId">The ID for the custom channel to be updated.</param> private void DeleteCustomChannel(string adClientId, string customChannelId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Deleting custom channel {0}", customChannelId); CommandLine.WriteLine("================================================================="); // Delete custom channel CustomChannel customChannel = this.service.Customchannels .Delete(adClientId, customChannelId).Execute(); // Delete nonexistent custom channel try { CustomChannel wrongcustomChannel = this.service.Customchannels .Delete(adClientId, "wrong_id").Execute(); } catch (Google.GoogleApiException ex) { CommandLine.WriteLine("Error with message '{0}' was correctly caught.", ex.Message); } CommandLine.WriteLine("Custom channel with id {0} was deleted.", customChannelId); CommandLine.WriteLine(); } /// <summary> /// This example gets all URL channels in an host ad client. /// </summary> /// <param name="adClientId">The ID for the ad client to be used.</param> private void GetAllUrlChannels(string adClientId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all URL channels for host ad client {0}", adClientId); CommandLine.WriteLine("================================================================="); // Retrieve URL channel list in pages and display data as we receive it. string pageToken = null; UrlChannels urlChannelResponse = null; do { var urlChannelRequest = this.service.Urlchannels.List(adClientId); urlChannelRequest.MaxResults = this.maxListPageSize; urlChannelRequest.PageToken = pageToken; urlChannelResponse = urlChannelRequest.Execute(); if (urlChannelResponse.Items != null && urlChannelResponse.Items.Count > 0) { foreach (var urlChannel in urlChannelResponse.Items) { CommandLine.WriteLine("URL channel with pattern \"{0}\" was found.", urlChannel.UrlPattern); } } else { CommandLine.WriteLine("No URL channels found."); } pageToken = urlChannelResponse.NextPageToken; } while (pageToken != null); CommandLine.WriteLine(); } /// <summary> /// This example adds a URL channel to a host ad client. /// </summary> /// <param name="adClientId">The ID for the ad client to be used.</param> /// <returns>The created URL channel.</returns> private UrlChannel AddUrlChannel(string adClientId) { UrlChannel newUrlChannel = new UrlChannel(); System.Random random = new System.Random(System.DateTime.Now.Millisecond); newUrlChannel.UrlPattern = "www.example.com/" + random.Next(0, 10000).ToString(); CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Adding URL channel to ad client {0} with pattern {1}", adClientId, newUrlChannel.UrlPattern); CommandLine.WriteLine("================================================================="); // Create URL channel. UrlChannel urlChannel = this.service.Urlchannels .Insert(newUrlChannel, adClientId).Execute(); CommandLine.WriteLine("URL channel with id {0} and URL pattern {1} was created", urlChannel.Id, urlChannel.UrlPattern); CommandLine.WriteLine(); // Return the URL Channel that was just created return urlChannel; } /// <summary> /// This example deletes a URL channel on a host ad client. /// </summary> /// <param name="adClientId">The ID for the ad client to be used.</param> /// <param name="urlChannelId">The ID for the URL channel to be deleted.</param> private void DeleteUrlChannel(string adClientId, string urlChannelId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Deleting URL channel {0}", urlChannelId); CommandLine.WriteLine("================================================================="); // Delete custom channel UrlChannel urlChannel = this.service.Urlchannels .Delete(adClientId, urlChannelId).Execute(); CommandLine.WriteLine("Custom channel with id {0} was deleted.", urlChannelId); CommandLine.WriteLine(); } /// <summary> /// This example prints a report, using a filter for a specified ad client. /// </summary> /// <param name="adsense">AdSense service object on which to run the requests.</param> /// <param name="adClientId">The ID for the ad client to be used.</param> private void GenerateReport(AdSenseHostService service, string adClientId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Running report for ad client {0}", adClientId); CommandLine.WriteLine("================================================================="); // Prepare report. var startDate = DateTime.Today.ToString(DateFormat); var endDate = DateTime.Today.AddDays(-7).ToString(DateFormat); ReportsResource.GenerateRequest reportRequest = this.service.Reports.Generate(startDate, endDate); // Specify the desired ad client using a filter, as well as other parameters. // A complete list of metrics and dimensions is available on the documentation. reportRequest.Filter = new List<string> { "AD_CLIENT_ID==" + ReportHelper.EscapeFilterParameter(adClientId) }; reportRequest.Metric = new List<string> { "PAGE_VIEWS", "AD_REQUESTS", "AD_REQUESTS_COVERAGE", "AD_REQUESTS_CTR", "COST_PER_CLICK", "AD_REQUESTS_RPM", "EARNINGS" }; reportRequest.Dimension = new List<string> { "DATE" }; //A list of dimensions to sort by: + means ascending, - means descending reportRequest.Sort = new List<string> { "+DATE" }; // Run report. Report reportResponse = reportRequest.Execute(); if (reportResponse.Rows != null && reportResponse.Rows.Count > 0) { ReportHelper.displayHeaders(reportResponse.Headers); ReportHelper.displayRows(reportResponse.Rows); } else { CommandLine.WriteLine("No rows returned."); } CommandLine.WriteLine(); } /// <summary> /// Finds the first Ad Client whose product code is AFC_HOST. /// </summary> /// <param name="adClients">List of ad clients.</param> /// <returns>Returns the first Ad Client whose product code is AFC_HOST.</returns> public static AdClient FindAdClientForHost(IList<AdClient> adClients) { if (adClients != null) { return adClients.First(ac => ac.ProductCode == "AFC_HOST"); } return null; } } }
zzfocuzz-deepbotcopy
AdSenseHost.Sample/HostApiConsumer.cs
C#
asf20
19,518
/* Copyright 2012 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using DotNetOpenAuth.OAuth2; using AdSenseHost.Sample.Host; using AdSenseHost.Sample.Publisher; using Google.Apis.Adsensehost.v4_1; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Util; namespace AdSenseHost.Sample { /// <summary> /// A sample application that runs multiple requests against the AdSense Host API /// <list type="bullet"> /// <item> /// <description>Host calls for your host account</description> /// </item> /// <item> /// <description>Publisher calls for your publisher's account (needs a Publisher ID)</description> /// </item> /// </list> /// </summary> internal class AdSenseHostSample { private static readonly string Scope = AdSenseHostService.Scopes.Adsensehost.GetStringValue(); private static readonly int MaxListPageSize = 50; [STAThread] static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("AdSense Host API Command Line Sample"); // Register the authenticator. FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials(); NativeApplicationClient provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = credentials.ClientId, ClientSecret = credentials.ClientSecret }; OAuth2Authenticator<NativeApplicationClient> auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication); // Create the service. var service = new AdSenseHostService(new BaseClientService.Initializer() { Authenticator = auth, ApplicationName = "AdSense API Sample", }); // Execute Host calls HostApiConsumer hostApiConsumer = new HostApiConsumer(service, MaxListPageSize); hostApiConsumer.RunCalls(); // Execute Publisher calls PublisherApiConsumer publisherApiConsumer = new PublisherApiConsumer(service, MaxListPageSize); publisherApiConsumer.RunCalls(); CommandLine.PressAnyKeyToExit(); } private static IAuthorizationState GetAuthentication(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.samples.dotnet.adsensehost"; const string KEY = "`b'[@d9(R4;.1Kr_ynFt"; IAuthorizationState state = null; try { // Check if there is a cached refresh token available. state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); } catch (System.Security.Cryptography.CryptographicException ex) { CommandLine.WriteError("Getting Refresh token failed: " + ex.Message); CommandLine.WriteLine("Requesting new authorization..."); state = null; } if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, Scope); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } } }
zzfocuzz-deepbotcopy
AdSenseHost.Sample/AdSenseHostSample.cs
C#
asf20
4,782
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AdSenseHost.Sample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google")] [assembly: AssemblyProduct("AdSenseHost.Sample")] [assembly: AssemblyCopyright("Copyright © Google Inc 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b6962508-f989-42d9-93c8-fec28dafcd3f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
AdSenseHost.Sample/Properties/AssemblyInfo.cs
C#
asf20
1,464
<html> <head> <title>Google .NET Client API &ndash; AdSenseHost.Sample</title> </head> <body> <h2> Instructions for the Google .NET Client API &ndash; AdSenseHost.Sample </h2> <h3> Browse Online </h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FAdSenseHost.Sample"> Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/AdSenseHost.Sample/Program.cs?repo=samples"> Program.cs</a>.</li> </ul> <h3> Checkout Instructions </h3> <p> <b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>. </p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code> </pre> <h3> Set up Project in Visual Studio </h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>AdSenseHost.Sample\bin\Debug</i></li> <li>When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/"> Google APIs Console</a> API Access pane. </li> </ul> <h3> Association Sessions </h3> <p>In order to run the association session calls, set <i>AssociationSessionSample.cs</i> as startup object of the project and rebuild.</p> </body> </html>
zzfocuzz-deepbotcopy
AdSenseHost.Sample/README.html
HTML
asf20
1,677
/* Copyright 2012 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using Google.Apis.Adsensehost.v4_1; using Google.Apis.Adsensehost.v4_1.Data; using Google.Apis.Samples.Helper; namespace AdSenseHost.Sample.Publisher { /// <summary> /// A sample consumer that runs multiple Host requests against the AdSense Host API. /// These include: /// <list type="bullet"> /// <item> /// <description>Getting a list of all publisher ad clients</description> /// </item> /// <item> /// <description>Getting a list of all publisher ad units</description> /// </item> /// <item> /// <description>Adding a new ad unit</description> /// </item> /// <item> /// <description>Updating an existing ad unit</description> /// </item> /// <item> /// <description>Deleting an ad unit</description> /// </item> /// <item> /// <description>Running a report for a publisher ad client, for the past 7 days</description> /// </item> /// </list> /// </summary> public class PublisherApiConsumer { AdSenseHostService service; int maxListPageSize; private static readonly string DateFormat = "yyyy-MM-dd"; /// <summary> /// Runs multiple Publisher requests against the AdSense Host API. /// </summary> /// <param name="service">AdSensehost service object on which to run the requests.</param> /// <param name="maxListPageSize">The maximum page size to retrieve.</param> public PublisherApiConsumer(AdSenseHostService service, int maxListPageSize) { this.service = service; this.maxListPageSize = maxListPageSize; } internal void RunCalls() { CommandLine.WriteLine("For the rest of the samples you'll need a Publisher ID. If you haven't " + "associated an AdSense account to your Host, set AssociationSession.cs as startup object " + "and rebuild."); // Get publisher ID from user. string publisherId = null; CommandLine.RequestUserInput("Insert Publisher ID", ref publisherId); if (publisherId == null) { return; } AdClients publisherAdClients = GetAllAdClients(publisherId); if (publisherAdClients.Items != null && publisherAdClients.Items.Count > 0) { // Get a host ad client ID, so we can run the rest of the samples. string examplePublisherAdClientId = publisherAdClients.Items[0].Id; GetAllAdUnits(publisherId, examplePublisherAdClientId); AdUnit adUnit = AddAdUnit(publisherId, examplePublisherAdClientId); adUnit = UpdateAdUnit(publisherId, examplePublisherAdClientId, adUnit.Id); DeleteAdUnit(publisherId, examplePublisherAdClientId, adUnit.Id); GenerateReport(publisherId, examplePublisherAdClientId); } } /// <summary> /// This example gets all ad clients for a publisher account. /// </summary> /// <param name="accountId">The ID for the publisher's account to be used.</param> /// <returns>The last page of retrieved ad clients.</returns> private AdClients GetAllAdClients(string accountId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all ad clients for account {0}", accountId); CommandLine.WriteLine("================================================================="); // Retrieve ad client list in pages and display data as we receive it. string pageToken = null; AdClients adClientResponse = null; do { var adClientRequest = this.service.Accounts.Adclients.List(accountId); adClientRequest.MaxResults = this.maxListPageSize; adClientRequest.PageToken = pageToken; adClientResponse = adClientRequest.Execute(); if (adClientResponse.Items != null && adClientResponse.Items.Count > 0) { foreach (var adClient in adClientResponse.Items) { CommandLine.WriteLine("Ad client for product \"{0}\" with ID \"{1}\" was found.", adClient.ProductCode, adClient.Id); CommandLine.WriteLine("\tSupports reporting: {0}", adClient.SupportsReporting.Value ? "Yes" : "No"); } } else { CommandLine.WriteLine("No ad clients found."); } pageToken = adClientResponse.NextPageToken; } while (pageToken != null); CommandLine.WriteLine(); // Return the last page of ad clients, so that the main sample has something to run. return adClientResponse; } /// <summary> /// This example prints all ad units in a publisher ad client. /// </summary> /// <param name="accountId">The ID for the publisher account to be used.</param> /// <param name="adClientId">An arbitrary publisher ad client ID.</param> private void GetAllAdUnits(string accountId, string adClientId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all ad units for ad client {0}", adClientId); CommandLine.WriteLine("================================================================="); // Retrieve ad client list in pages and display data as we receive it. string pageToken = null; AdUnits adUnitResponse = null; do { var adUnitRequest = this.service.Accounts.Adunits.List(accountId, adClientId); adUnitRequest.MaxResults = this.maxListPageSize; adUnitRequest.PageToken = pageToken; adUnitResponse = adUnitRequest.Execute(); if (adUnitResponse.Items != null && adUnitResponse.Items.Count > 0) { foreach (var adUnit in adUnitResponse.Items) { CommandLine.WriteLine("Ad unit with code \"{0}\", name \"{1}\" and status \"{2}\" " + "was found.", adUnit.Code, adUnit.Name, adUnit.Status); } } else { CommandLine.WriteLine("No ad units found."); } pageToken = adUnitResponse.NextPageToken; } while (pageToken != null); CommandLine.WriteLine(); } /// <summary> /// This example adds a new ad unit to a publisher ad client. /// </summary> /// <param name="accountId">The ID for the publisher account to be used.</param> /// <param name="adClientId">An arbitrary publisher ad client ID.</param> /// <returns>The created ad unit.</returns> private AdUnit AddAdUnit(string accountId, string adClientId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Adding ad unit to ad client {0}", accountId); CommandLine.WriteLine("================================================================="); AdUnit newAdUnit = new AdUnit(); Random random = new Random(DateTime.Now.Millisecond); newAdUnit.Name = "Ad Unit #" + random.Next(0, 10000).ToString(); newAdUnit.ContentAdsSettings = new AdUnit.ContentAdsSettingsData(); newAdUnit.ContentAdsSettings.BackupOption = new AdUnit.ContentAdsSettingsData.BackupOptionData(); newAdUnit.ContentAdsSettings.BackupOption.Type = "COLOR"; newAdUnit.ContentAdsSettings.BackupOption.Color = "ffffff"; newAdUnit.ContentAdsSettings.Size = "SIZE_200_200"; newAdUnit.ContentAdsSettings.Type = "TEXT"; newAdUnit.CustomStyle = new AdStyle(); newAdUnit.CustomStyle.Colors = new AdStyle.ColorsData(); newAdUnit.CustomStyle.Colors.Background = "ffffff"; newAdUnit.CustomStyle.Colors.Border = "000000"; newAdUnit.CustomStyle.Colors.Text = "000000"; newAdUnit.CustomStyle.Colors.Title = "000000"; newAdUnit.CustomStyle.Colors.Url = "0000ff"; newAdUnit.CustomStyle.Corners = "SQUARE"; newAdUnit.CustomStyle.Font = new AdStyle.FontData(); newAdUnit.CustomStyle.Font.Family = "ACCOUNT_DEFAULT_FAMILY"; newAdUnit.CustomStyle.Font.Size = "ACCOUNT_DEFAULT_SIZE"; // Create ad unit. AccountsResource.AdunitsResource.InsertRequest insertRequest = this.service.Accounts.Adunits .Insert(newAdUnit, accountId, adClientId); AdUnit adUnit = insertRequest.Execute(); CommandLine.WriteLine("Ad unit of type {0}, name {1} and status {2} was created", adUnit.ContentAdsSettings.Type, adUnit.Name, adUnit.Status); CommandLine.WriteLine(); // Return the Ad Unit that was just created return adUnit; } /// <summary> /// This example updates an ad unit on a publisher ad client. /// </summary> /// <param name="accountId">The ID for the publisher account to be used.</param> /// <param name="adClientId">An arbitrary publisher ad client ID.</param> /// <param name="adUnitId">The ID of the ad unit to be updated.</param> /// <returns>The updated custom channel.</returns> private AdUnit UpdateAdUnit(string accountId, string adClientId, string adUnitId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Updating ad unit {0}", adUnitId); CommandLine.WriteLine("================================================================="); AdUnit patchAdUnit = new AdUnit(); patchAdUnit.CustomStyle = new AdStyle(); patchAdUnit.CustomStyle.Colors = new AdStyle.ColorsData(); patchAdUnit.CustomStyle.Colors.Text = "ff0000"; // Update custom channel: Using REST's PATCH method to update just the Name field. AdUnit adUnit = this.service.Accounts.Adunits .Patch(patchAdUnit, accountId, adClientId, adUnitId).Execute(); CommandLine.WriteLine("Ad unit with id {0}, was updated with text color {1}.", adUnit.Id, adUnit.CustomStyle.Colors.Text); CommandLine.WriteLine(); // Return the Ad Unit that was just created return adUnit; } /// <summary> /// This example deletes an Ad Unit on a publisher ad client. /// </summary> /// <param name="accountId">The ID for the publisher account to be used.</param> /// <param name="adClientId">The ID for the ad client to be used.</param> /// <param name="adUnitId">The ID for the Ad Unit to be deleted.</param> private void DeleteAdUnit(string accountId, string adClientId, string adUnitId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Deleting ad unit {0}", adUnitId); CommandLine.WriteLine("================================================================="); // Delete ad unit AdUnit adUnit = this.service.Accounts.Adunits .Delete(accountId, adClientId, adUnitId).Execute(); CommandLine.WriteLine("Ad unit with id {0} was deleted.", adUnitId); CommandLine.WriteLine(); } /// <summary> /// This example retrieves a report for the specified publisher ad client. /// /// Note that the statistics returned in these reports only include data from ad /// units created with the AdSense Host API v4.x. /// </summary> /// <param name="accountId">The ID of the publisher account on which to run the report.</param> /// <param name="adClientId">The ID for the ad client to be used.</param> private void GenerateReport(string accountId, string adClientId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Running report for ad client {0}", adClientId); CommandLine.WriteLine("================================================================="); // Prepare report. var startDate = DateTime.Today.ToString(DateFormat); var endDate = DateTime.Today.AddDays(-7).ToString(DateFormat); AccountsResource.ReportsResource.GenerateRequest reportRequest = this.service.Accounts.Reports.Generate(accountId, startDate, endDate); // Specify the desired ad client using a filter, as well as other parameters. // A complete list of metrics and dimensions is available on the documentation. reportRequest.Filter = new List<string> { "AD_CLIENT_ID==" + ReportHelper.EscapeFilterParameter(adClientId) }; reportRequest.Metric = new List<string> { "PAGE_VIEWS", "AD_REQUESTS", "AD_REQUESTS_COVERAGE", "CLICKS", "AD_REQUESTS_CTR", "COST_PER_CLICK", "AD_REQUESTS_RPM", "EARNINGS" }; reportRequest.Dimension = new List<string> { "DATE" }; //A list of dimensions to sort by: + means ascending, - means descending reportRequest.Sort = new List<string> { "+DATE" }; // Run report. Report reportResponse = reportRequest.Execute(); if (reportResponse.Rows != null && reportResponse.Rows.Count > 0) { ReportHelper.displayHeaders(reportResponse.Headers); ReportHelper.displayRows(reportResponse.Rows); } else { CommandLine.WriteLine("No rows returned."); } CommandLine.WriteLine(); } } }
zzfocuzz-deepbotcopy
AdSenseHost.Sample/PublisherApiConsumer.cs
C#
asf20
15,462
/* Copyright 2012 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Google.Apis.Adsensehost.v4_1.Data; using Google.Apis.Samples.Helper; namespace AdSenseHost.Sample { internal class ReportHelper { /// <summary> /// Displays the headers for the report. /// </summary> /// <param name="headers">The list of headers to be displayed</param> internal static void displayHeaders(IList<Report.HeadersData> headers) { foreach (var header in headers) { CommandLine.Write("{0, -25}", header.Name); } CommandLine.WriteLine(); } /// <summary> /// Displays a list of rows for the report. /// </summary> /// <param name="rows">The list of rows to display.</param> internal static void displayRows(IList<IList<String>> rows) { foreach (var row in rows) { foreach (var column in row) { CommandLine.Write("{0, -25}", column); } CommandLine.WriteLine(); } } /// <summary> /// Escape special characters for a parameter being used in a filter. /// </summary> /// <param name="parameter">The parameter to be escaped.</param> /// <returns>The escaped parameter.</returns> internal static string EscapeFilterParameter(string parameter) { return parameter.Replace("\\", "\\\\").Replace(",", "\\,"); } } }
zzfocuzz-deepbotcopy
AdSenseHost.Sample/ReportHelper.cs
C#
asf20
2,224
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Books.ListMyLibrary")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("Books.v1.ListMyLibrary")] [assembly: AssemblyCopyright("Copyright © Google Inc 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("43e33418-eef3-4859-aac2-ff1615229840")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
Books.ListMyLibrary/Properties/AssemblyInfo.cs
C#
asf20
1,473
<html> <title>Google .NET Client API &ndash; Books.ListMyLibrary</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Books.ListMyLibrary</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FBooks.ListMyLibrary">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Books.ListMyLibrary/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Books API for your project </li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Books.ListMyLibrary\bin\Debug</i></li> <li> When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane. </li> </ul> </body> </html>
zzfocuzz-deepbotcopy
Books.ListMyLibrary/README.html
HTML
asf20
1,648
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Threading.Tasks; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Books.v1; using Google.Apis.Books.v1.Data; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Util; namespace Books.ListMyLibrary { /// <summary> /// Sample which demonstrates how to use the Books API. /// Lists all volumes in the the users library, and retrieves more detailed information about the first volume. /// https://code.google.com/apis/books/docs/v1/getting_started.html /// </summary> internal class Program { private static readonly string Scope = BooksService.Scopes.Books.GetStringValue(); [STAThread] static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Books API: List MyLibrary"); // Register the authenticator. FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials(); var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = credentials.ClientId, ClientSecret = credentials.ClientSecret }; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication); // Create the service. var service = new BooksService(new BaseClientService.Initializer() { Authenticator = auth, ApplicationName = "Books API Sample", }); ListLibrary(service); Console.ReadLine(); } private static IAuthorizationState GetAuthentication(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.samples.dotnet.books"; const string KEY = "=UwuqAtRaqe-3daV"; // Check if there is a cached refresh token available. IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, Scope); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } private static void ListLibrary(BooksService service) { CommandLine.WriteAction("Listing Bookshelves... (using async execution)"); // execute async var task = service.Mylibrary.Bookshelves.List().ExecuteAsync(); // on success display my library's volumes CommandLine.WriteLine(); task.ContinueWith(async t => await DisplayVolumes(service, t.Result), TaskContinuationOptions.OnlyOnRanToCompletion); // on failure print the error task.ContinueWith(t => { CommandLine.Write("Error occurred on executing async operation"); if (t.IsCanceled) { CommandLine.Write("Task was canceled"); } if (t.Exception != null) { CommandLine.Write("exception occurred. Exception is " + t.Exception.Message); } }, TaskContinuationOptions.NotOnRanToCompletion); } private static async Task DisplayVolumes(BooksService service, Bookshelves bookshelves) { if (bookshelves.Items == null) { CommandLine.WriteError("No bookshelves found!"); return; } foreach (Bookshelf item in bookshelves.Items) { CommandLine.WriteResult(item.Title, item.VolumeCount + " volumes"); // List all volumes in this bookshelf. if (item.VolumeCount > 0) { CommandLine.WriteAction("Query volumes... (Execute Async)"); var request = service.Mylibrary.Bookshelves.Volumes.List(item.Id.ToString()); Volumes inBookshelf = await request.ExecuteAsync(); if (inBookshelf.Items == null) { continue; } foreach (Volume volume in inBookshelf.Items) { CommandLine.WriteResult( "-- " + volume.VolumeInfo.Title, volume.VolumeInfo.Description ?? "no description"); } } } } } }
zzfocuzz-deepbotcopy
Books.ListMyLibrary/Program.cs
C#
asf20
6,149
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using Google.Apis.Tasks.v1.Data; namespace TasksExample.WinForms.NoteMgr { /// <summary> /// A single graphical note. /// </summary> public partial class NoteItem : UserControl { /// <summary> /// The text this note contains. /// </summary> [Category("Note")] public string NoteText { get { return text.Text; } set { text.Text = value; } } /// <summary> /// Whether this note is finished or not. /// </summary> [Category("Note")] public bool NoteFinished { get { return checkbox.Checked; } set { checkbox.Checked = value; } } /// <summary> /// The related remote task. /// </summary> public Task RelatedTask { get; set; } /// <summary> /// Called whenever the user wants to create a new note. /// </summary> public event Action NewNoteRequest; /// <summary> /// Called whenever the user wants to delete a note. /// </summary> public event Action<NoteItem> DeleteNoteRequest; /// <summary> /// Called whenever this note is changed by the user. /// </summary> public event Action<NoteItem> OnNoteChanged; public NoteItem() { InitializeComponent(); Dock = DockStyle.Top; } /// <summary> /// Creates a new note item and associates the action events with the specified NoteForm. /// </summary> public NoteItem(NoteForm form, Task relatedTask) : this() { NewNoteRequest += form.AddNote; DeleteNoteRequest += form.DeleteNote; RelatedTask = relatedTask; if (relatedTask != null) { // Use data from the related task. NoteText = relatedTask.Title; NoteFinished = relatedTask.Status == "completed"; } } /// <summary> /// Focuses this note. /// </summary> public void FocusNote() { text.Focus(); } /// <summary> /// Synchronizes changes between this visual note and the related task. /// </summary> /// <returns>True if there have been any changes.</returns> public bool ClientSync() { if (RelatedTask == null) { RelatedTask = new Task(); RelatedTask.Title = NoteText; RelatedTask.Status = NoteFinished ? "completed" : "needsAction"; return true; // Nothing to sync here. } bool changes = false; // Detect changes. if (NoteText != RelatedTask.Title) { RelatedTask.Title = NoteText; changes = true; } if (NoteFinished != (!string.IsNullOrEmpty(RelatedTask.Completed))) { RelatedTask.Status = NoteFinished ? "completed" : "needsAction"; changes = true; } return changes; } private void NoteItem_Paint(object sender, PaintEventArgs e) { // Draw a small, red line on the bottom. int y = ClientSize.Height - 1; e.Graphics.DrawLine(Pens.Pink, 0, y, ClientSize.Width, y); } private void text_KeyDown(object sender, KeyEventArgs e) { if (text.Text.Length == 0 && e.KeyCode == Keys.Back && DeleteNoteRequest != null) { // Delete request. DeleteNoteRequest(this); } else if (text.Text.Length > 0 && e.KeyCode == Keys.Enter && NewNoteRequest != null) { // New note request. NewNoteRequest(); } } private void text_TextChanged(object sender, EventArgs e) { if (text.TextLength > 0 && OnNoteChanged != null) { OnNoteChanged(this); } } private void checkbox_CheckedChanged(object sender, EventArgs e) { text.Font = new Font(text.Font, checkbox.Checked ? FontStyle.Strikeout : FontStyle.Regular); text.ForeColor = checkbox.Checked ? Color.DarkGray : Color.Black; } } }
zzfocuzz-deepbotcopy
Tasks.WinForms.NoteMgr/NoteItem.cs
C#
asf20
5,238
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Tasks.WinForms.NoteMgr")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("Tasks.WinForms.NoteMgr")] [assembly: AssemblyCopyright("Copyright © Google Inc 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("093e2a22-deda-4890-98cb-4d8edb3051c7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
Tasks.WinForms.NoteMgr/Properties/AssemblyInfo.cs
C#
asf20
1,476
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using Google.Apis.Samples.Helper; namespace TasksExample.WinForms.NoteMgr { /// <summary> /// This class provides the client credentials for all the samples in this solution. /// In order to run all of the samples, you have to enable API access for every API /// you want to use, enter your credentials here. /// /// You can find your credentials here: /// https://code.google.com/apis/console/#:access /// /// For your own application you should find a more secure way than just storing your client secret inside a string, /// as it can be lookup up easily using a reflection tool. /// </summary> internal static class ClientCredentials { /// <summary> /// The OAuth2.0 Client ID of your project. /// </summary> public static readonly string ClientID = "<Enter your ClientID here>"; /// <summary> /// The OAuth2.0 Client secret of your project. /// </summary> public static readonly string ClientSecret = "<Enter your ClientSecret here>"; /// <summary> /// Your Api/Developer key. /// </summary> public static readonly string ApiKey = "<Enter your ApiKey here>"; #region Verify Credentials static ClientCredentials() { ReflectionUtils.VerifyCredentials(typeof(ClientCredentials)); } #endregion } }
zzfocuzz-deepbotcopy
Tasks.WinForms.NoteMgr/ClientCredentials.cs
C#
asf20
2,024
<html> <title>Google .NET Client API &ndash; Tasks.WinForms.NoteMgr</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Tasks.WinForms.NoteMgr</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FTasks.WinForms.NoteMgr">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.WinForms.NoteMgr/NoteForm.cs?repo=samples">NoteForm.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Tasks API for your project </li> <li>Edit <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.WinForms.NoteMgr/ClientCredentials.cs?repo=samples">ClientCredentials.cs</a> to insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane.</li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Tasks.WinForms.NoteMgr\bin\Debug</i></li> </ul> </body> </html>
zzfocuzz-deepbotcopy
Tasks.WinForms.NoteMgr/README.html
HTML
asf20
1,806
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Threading; using System.Windows.Forms; using Google.Apis.Tasks.v1.Data; namespace TasksExample.WinForms.NoteMgr { /// <summary> /// Visual representation of a tasklist. /// </summary> public partial class NoteForm : Form { private readonly List<NoteItem> deletedNotes = new List<NoteItem>(); private readonly TaskList taskList; private readonly object sync = new object(); public NoteForm() { InitializeComponent(); AddNote(); } public NoteForm(TaskList taskList) { InitializeComponent(); this.taskList = taskList; // Set the title. Text = taskList.Title; // Load all notes: Tasks tasks = Program.Service.Tasks.List(taskList.Id).Execute(); if (tasks.Items != null) { foreach (Task task in tasks.Items) { AddNote(task); } } else { AddNote(); } } /// <summary> /// Adds a new empty note to the note list. /// </summary> public void AddNote() { AddNote(null).FocusNote(); } /// <summary> /// Loads the specified note and adds it to the form. /// </summary> /// <param name="task"></param> /// <returns></returns> public NoteItem AddNote(Task task) { var newNote = new NoteItem(this, task); // Insert the new control as the first element, as it will be displayed on the bottom. var all = (from Control c in Controls select c).ToArray(); SuspendLayout(); Controls.Clear(); Controls.Add(newNote); Controls.AddRange(all); UpdateHeight(); ResumeLayout(); return newNote; } /// <summary> /// Deletes a note from the note list. /// </summary> public void DeleteNote(NoteItem note) { if (Controls.Count <= 1) { return; // Don't remove the last note. } Controls.Remove(note); deletedNotes.Add(note); ((NoteItem)Controls[0]).FocusNote(); UpdateHeight(); } /// <summary> /// Synchronizes this client with the remote server. /// </summary> public void ClientSync() { // TODO(mlinder): Implement batching here. lock (sync) { var requests = new List<Action>(); // Add changes/inserts. NoteItem previous = null; foreach (NoteItem currentNote in (from Control c in Controls where c is NoteItem select c).Reverse()) { NoteItem note = currentNote; if (note.ClientSync()) { bool isNew = String.IsNullOrEmpty(note.RelatedTask.Id); requests.AddRange(GetSyncNoteRequest(note, previous, isNew)); } previous = note; } // Add deletes. foreach (NoteItem note in deletedNotes) { NoteItem noteb = note; if(note.RelatedTask != null && !String.IsNullOrEmpty(note.RelatedTask.Id)) requests.Add(() => Program.Service.Tasks.Delete(taskList.Id, noteb.RelatedTask.Id).Execute()); } deletedNotes.Clear(); // Execute all requests. requests.ForEach(action => action()); } } private IEnumerable<Action> GetSyncNoteRequest(NoteItem note, NoteItem previous, bool isNew) { var tasks = Program.Service.Tasks; if (isNew) { NoteItem previousSaved = previous; yield return () => note.RelatedTask = tasks.Insert(note.RelatedTask, taskList.Id).Execute(); yield return () => { var req = tasks.Move(taskList.Id, note.RelatedTask.Id); if (previousSaved != null) { req.Previous = previousSaved.RelatedTask.Id; } note.RelatedTask = req.Execute(); }; } else { yield return () => { var req = tasks.Update(note.RelatedTask, taskList.Id, note.RelatedTask.Id); note.RelatedTask = req.Execute(); }; } } private void UpdateHeight() { // Change the height of the list to contain all items. int totalY = 0; foreach (Control c in Controls) { totalY += c.Height; } ClientSize = new Size(ClientSize.Width, totalY); } private void NoteForm_Shown(object sender, System.EventArgs e) { // Add a sync timer. var timer = new System.Windows.Forms.Timer(); timer.Interval = 1000 * 60 * 5; // 5 min timer.Tick += (timerSender, timerArgs) => ClientSync(); timer.Start(); // Focus the first note. if (Controls.Count > 0) { ((NoteItem)Controls[0]).FocusNote(); } } private void NoteForm_FormClosing(object sender, FormClosingEventArgs e) { ClientSync(); Application.DoEvents(); lock (sync) {} } private void NoteForm_Deactivate(object sender, EventArgs e) { if (Disposing) { return; } // Sync asynchronously. ThreadPool.QueueUserWorkItem((obj) => ClientSync()); } private void NoteForm_FormClosed(object sender, FormClosedEventArgs e) { if (Application.OpenForms.Count == 0) { // If no more forms are open, exit the WinForms worker thread. Application.Exit(); } } } }
zzfocuzz-deepbotcopy
Tasks.WinForms.NoteMgr/NoteForm.cs
C#
asf20
7,504
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Windows.Forms; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Tasks.v1; using Google.Apis.Tasks.v1.Data; using Google.Apis.Util; namespace TasksExample.WinForms.NoteMgr { /// <summary> /// Note Manager /// A more complex example for the tasks API. /// </summary> internal static class Program { /// <summary> /// The remote service on which all the requests are executed. /// </summary> public static TasksService Service { get; private set; } private static IAuthenticator CreateAuthenticator() { var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = ClientCredentials.ClientID; provider.ClientSecret = ClientCredentials.ClientSecret; return new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication); } private static IAuthorizationState GetAuthentication(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.samples.dotnet.tasks"; const string KEY = "y},drdzf11x9;87"; string scope = TasksService.Scopes.Tasks.GetStringValue(); // Check if there is a cached refresh token available. IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, scope); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Initialize the service. Service = new TasksService(new BaseClientService.Initializer() { Authenticator = CreateAuthenticator(), ApplicationName = "Tasks API Sample" }); // Open a NoteForm for every task list. foreach (TaskList list in Service.Tasklists.List().Execute().Items) { // Open a NoteForm. new NoteForm(list).Show(); } Application.Run(); } } }
zzfocuzz-deepbotcopy
Tasks.WinForms.NoteMgr/Program.cs
C#
asf20
3,903
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Discovery.ListAPIs")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google")] [assembly: AssemblyProduct("Discovery.ListAPIs")] [assembly: AssemblyCopyright("Copyright © Google 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("786ae493-79cb-4e1c-b33e-dbf79a6ef926")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
Discovery.ListAPIs/Properties/AssemblyInfo.cs
C#
asf20
1,460
<html> <title>Google .NET Client API &ndash; Discovery.ListAPIs</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Discovery.ListAPIs</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FDiscovery.ListAPIs">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Discovery.ListAPIs/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Discovery.ListAPIs\bin\Debug</i></li> </ul> </body> </html>
zzfocuzz-deepbotcopy
Discovery.ListAPIs/README.html
HTML
asf20
1,049
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using Google.Apis.Discovery.v1; using Google.Apis.Discovery.v1.Data; using Google.Apis.Samples.Helper; namespace Discovery.ListAPIs { /// <summary> /// This example uses the discovery API to list all APIs in the discovery repository. /// http://code.google.com/apis/discovery/v1/using.html /// </summary> class Program { [STAThread] static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Discovery API"); // Create the service. var service = new DiscoveryService(); RunSample(service); CommandLine.PressAnyKeyToExit(); } private static void RunSample(DiscoveryService service) { // Run the request. CommandLine.WriteAction("Executing List-request ..."); var result = service.Apis.List().Execute(); // Display the results. if (result.Items != null) { foreach (DirectoryList.ItemsData api in result.Items) { CommandLine.WriteResult(api.Id, api.Title); } } } } }
zzfocuzz-deepbotcopy
Discovery.ListAPIs/Program.cs
C#
asf20
1,923
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Prediction.HostedExample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("Prediction.HostedExample")] [assembly: AssemblyCopyright("Copyright © Google Inc 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ad347a2d-5977-4df6-96ab-42f36aed3d6a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
Prediction.HostedExample/Properties/AssemblyInfo.cs
C#
asf20
1,480
<html> <title>Google .NET Client API &ndash; Prediction.HostedExample</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Prediction.HostedExample</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FPrediction.HostedExample">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Prediction.HostedExample/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Prediction API and Google Storage for your project </li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Prediction.HostedExample\bin\Debug</i></li> <li> When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane. </li> </ul> </body> </html>
zzfocuzz-deepbotcopy
Prediction.HostedExample/README.html
HTML
asf20
1,697
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Prediction.v1_3; using Google.Apis.Prediction.v1_3.Data; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Util; namespace Prediction.HostedExample { /// <summary> /// Sample for the prediction API. /// This sample makes use of the predefined "Language Identifier" demo prediction set. /// http://code.google.com/apis/predict/docs/gallery.html /// </summary> internal class Program { [STAThread] static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Prediction API"); CommandLine.WriteLine(); // Register the authenticator. FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials(); var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = credentials.ClientId, ClientSecret = credentials.ClientSecret }; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication); // Create the service. var service = new PredictionService(new BaseClientService.Initializer() { Authenticator = auth, ApplicationName = "Prediction API Sample", }); RunPrediction(service); CommandLine.PressAnyKeyToExit(); } private static IAuthorizationState GetAuthentication(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.samples.dotnet.prediction"; const string KEY = "AF41sdBra7ufra)VD:@#A#a++=3e"; string scope = PredictionService.Scopes.Prediction.GetStringValue(); // Check if there is a cached refresh token available. IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, scope); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } private static void RunPrediction(PredictionService service) { // Make a prediction. CommandLine.WriteAction("Performing a prediction..."); string text = "mucho bueno"; CommandLine.RequestUserInput("Text to analyze", ref text); var input = new Input { InputValue = new Input.InputData { CsvInstance = new List<string> { text } } }; Output result = service.Hostedmodels.Predict(input, "sample.languageid").Execute(); CommandLine.WriteResult("Language", result.OutputLabel); } } }
zzfocuzz-deepbotcopy
Prediction.HostedExample/Program.cs
C#
asf20
4,354
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Discovery.FieldsParameter")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Discovery.FieldsParameter")] [assembly: AssemblyCopyright("Copyright © Microsoft 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cfa5ff7c-65fc-4c2b-898c-330bdc7d8a0f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
Discovery.FieldsParameter/Properties/AssemblyInfo.cs
C#
asf20
1,480
<html> <title>Google .NET Client API &ndash; Discovery.FieldsParameter</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Discovery.FieldsParameter</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FDiscovery.FieldsParameter">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Discovery.FieldsParameter/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Discovery.FieldsParameter\bin\Debug</i></li> </ul> </body> </html>
zzfocuzz-deepbotcopy
Discovery.FieldsParameter/README.html
HTML
asf20
1,084
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using Google.Apis.Discovery.v1; using Google.Apis.Discovery.v1.Data; using Google.Apis.Samples.Helper; namespace Discovery.FieldsParameter { /// <summary> /// This example demonstrates how to do a Partial GET using field parameters. /// http://code.google.com/apis/discovery/v1/using.html /// </summary> class Program { [STAThread] static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Discovery API -- 'Fields'-Parameter"); // Create the service. var service = new DiscoveryService(); RunSample(service); CommandLine.PressAnyKeyToExit(); } private static void RunSample(DiscoveryService service) { // Run the request. CommandLine.WriteAction("Executing Partial GET ..."); var request = service.Apis.GetRest("discovery", "v1"); request.Fields = "description,title"; var result = request.Execute(); // Display the results. CommandLine.WriteResult("Description", result.Description); CommandLine.WriteResult("Title", result.Title); CommandLine.WriteResult("Name (not requested)", result.Name); } } }
zzfocuzz-deepbotcopy
Discovery.FieldsParameter/Program.cs
C#
asf20
2,016
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Linq; using System.Reflection; using System.Security.Authentication; using System.Security.Cryptography; using System.Text; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Samples.Helper.NativeAuthorizationFlows; namespace Google.Apis.Samples.Helper { /// <summary> /// Authorization helper for Native Applications. /// </summary> public static class AuthorizationMgr { private static readonly INativeAuthorizationFlow[] NativeFlows = new INativeAuthorizationFlow[] { new LoopbackServerAuthorizationFlow(), new WindowTitleNativeAuthorizationFlow() }; /// <summary> /// Requests authorization on a native client by using a predefined set of authorization flows. /// </summary> /// <param name="client">The client used for authentication.</param> /// <param name="authState">The requested authorization state.</param> /// <returns>The authorization code, or null if cancelled by the user.</returns> /// <exception cref="NotSupportedException">Thrown if no supported flow was found.</exception> public static string RequestNativeAuthorization(NativeApplicationClient client, IAuthorizationState authState) { // Try each available flow until we get an authorization / error. foreach (INativeAuthorizationFlow flow in NativeFlows) { try { return flow.RetrieveAuthorization(client, authState); } catch (NotSupportedException) { /* Flow unsupported on this environment */ } } throw new NotSupportedException("Found no supported native authorization flow."); } /// <summary> /// Requests authorization on a native client by using a predefined set of authorization flows. /// </summary> /// <param name="client">The client used for authorization.</param> /// <param name="scopes">The requested set of scopes.</param> /// <returns>The authorized state.</returns> /// <exception cref="AuthenticationException">Thrown if the request was cancelled by the user.</exception> public static IAuthorizationState RequestNativeAuthorization(NativeApplicationClient client, params string[] scopes) { IAuthorizationState state = new AuthorizationState(scopes); string authCode = RequestNativeAuthorization(client, state); if (string.IsNullOrEmpty(authCode)) { throw new AuthenticationException("The authentication request was cancelled by the user."); } return client.ProcessUserAuthorization(authCode, state); } /// <summary> /// Returns a cached refresh token for this application, or null if unavailable. /// </summary> /// <param name="storageName">The file name (without extension) used for storage.</param> /// <param name="key">The key to decrypt the data with.</param> /// <returns>The authorization state containing a Refresh Token, or null if unavailable</returns> public static AuthorizationState GetCachedRefreshToken(string storageName, string key) { string file = storageName + ".auth"; byte[] contents = AppData.ReadFile(file); if (contents == null) { return null; // No cached token available. } byte[] salt = Encoding.Unicode.GetBytes(Assembly.GetEntryAssembly().FullName + key); byte[] decrypted = ProtectedData.Unprotect(contents, salt, DataProtectionScope.CurrentUser); string[] content = Encoding.Unicode.GetString(decrypted).Split(new[] { "\r\n" }, StringSplitOptions.None); // Create the authorization state. string[] scopes = content[0].Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); string refreshToken = content[1]; return new AuthorizationState(scopes) { RefreshToken = refreshToken }; } /// <summary> /// Saves a refresh token to the specified storage name, and encrypts it using the specified key. /// </summary> public static void SetCachedRefreshToken(string storageName, string key, IAuthorizationState state) { // Create the file content. string scopes = state.Scope.Aggregate("", (left, append) => left + " " + append); string content = scopes + "\r\n" + state.RefreshToken; // Encrypt it. byte[] salt = Encoding.Unicode.GetBytes(Assembly.GetEntryAssembly().FullName + key); byte[] encrypted = ProtectedData.Protect( Encoding.Unicode.GetBytes(content), salt, DataProtectionScope.CurrentUser); // Save the data to the auth file. string file = storageName + ".auth"; AppData.WriteFile(file, encrypted); } } }
zzfocuzz-deepbotcopy
SampleHelper/AuthorizationMgr.cs
C#
asf20
6,289
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.IO; namespace Google.Apis.Samples.Helper { /// <summary> /// Provides access to the user's "AppData" folder /// </summary> public static class AppData { /// <summary> /// Path to the Application specific %AppData% folder. /// </summary> public static string SpecificPath { get { string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); return Path.Combine(appData, Util.ApplicationName); } } /// <summary> /// Returns the path to the specified AppData file. Ensures that the AppData folder exists. /// </summary> public static string GetFilePath(string file) { string dir = SpecificPath; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } return Path.Combine(SpecificPath, file); } /// <summary> /// Reads the specific file (if it exists), or returns null otherwise. /// </summary> /// <returns>File contents or null.</returns> public static byte[] ReadFile(string file) { string path = GetFilePath(file); return File.Exists(path) ? File.ReadAllBytes(path) : null; } /// <summary> /// Returns true if the specified file exists in this AppData folder. /// </summary> public static bool Exists(string file) { return File.Exists(GetFilePath(file)); } /// <summary> /// Writes the content to the specified file. Will create directories and files as necessary. /// </summary> public static void WriteFile(string file, byte[] contents) { string path = GetFilePath(file); File.WriteAllBytes(path, contents); } } }
zzfocuzz-deepbotcopy
SampleHelper/AppData.cs
C#
asf20
2,599
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.IO; using System.Reflection; using System.Text.RegularExpressions; namespace Google.Apis.Samples.Helper { /// <summary> /// Contains helper methods for command line operation /// </summary> public static class CommandLine { private static readonly Regex ColorRegex = new Regex("{([a-z]+)}", RegexOptions.Compiled); /// <summary> /// Defines whether this CommandLine can be accessed by an user and is thereby interactive. /// True by default. /// </summary> public static bool IsInteractive { get; set; } static CommandLine() { IsInteractive = true; } /// <summary> /// Creates a new instance of T and fills all public fields by requesting input from the user /// </summary> /// <typeparam name="T">Class with a default constructor</typeparam> /// <returns>Instance of T with filled in public fields</returns> public static T CreateClassFromUserinput<T>() { var type = typeof (T); // Create an instance of T T settings = Activator.CreateInstance<T>(); WriteLine("^1 Please enter values for the {0}:", ReflectionUtils.GetDescriptiveName(type)); // Fill in parameters foreach (FieldInfo field in type.GetFields(BindingFlags.Public | BindingFlags.Instance)) { object value = field.GetValue(settings); // Let the user input a value RequestUserInput(ReflectionUtils.GetDescriptiveName(field), ref value, field.FieldType); field.SetValue(settings, value); } WriteLine(); return settings; } /// <summary> /// Requests an user input for the specified value /// </summary> /// <param name="name">Name to display</param> /// <param name="value">Default value, and target value</param> public static void RequestUserInput<T>(string name, ref T value) { object val = value; RequestUserInput(name, ref val, typeof(T)); value = (T) val; } /// <summary> /// Requests an user input for the specified value, and returns the entered value. /// </summary> /// <param name="name">Name to display</param> public static T RequestUserInput<T>(string name) { object val = default(T); RequestUserInput(name, ref val, typeof(T)); return (T) val; } /// <summary> /// Requests an user input for the specified value /// </summary> /// <param name="name">Name to display</param> /// <param name="value">Default value, and target value</param> /// <param name="valueType">Type of the target value</param> private static void RequestUserInput(string name, ref object value, Type valueType) { do { if (value != null) { Write(" ^1{0} [^8{1}^1]: ^9", name, value); } else { Write(" ^1{0}: ^9", name); } string input = Console.ReadLine(); if (string.IsNullOrEmpty(input)) { return; // No change required } try { value = Convert.ChangeType(input, valueType); return; } catch (InvalidCastException) { WriteLine(" ^6Please enter a valid value!"); } } while (true); // Run this loop until the user gives a valid input } /// <summary> /// Displays the Google Sample Header /// </summary> public static void DisplayGoogleSampleHeader(string applicationName) { applicationName.ThrowIfNull("applicationName"); Console.BackgroundColor = ConsoleColor.Black; try { Console.Clear(); } catch (IOException) { } // An exception might occur if the console stream has been redirected. WriteLine(@"^3 ___ ^6 ^8 ^3 ^4 _ ^6 "); WriteLine(@"^3 / __| ^6 ___ ^8 ___ ^3 __ _ ^4| | ^6 __ "); WriteLine(@"^3 | (_ \ ^6/ _ \ ^8/ _ \ ^3/ _` | ^4| | ^6/-_) "); WriteLine(@"^3 \___| ^6\___/ ^8\___/ ^3\__, | ^4|_| ^6\___| "); WriteLine(@"^3 ^6 ^8 ^3|___/ ^4 ^6 "); WriteLine(); WriteLine("^4 API Samples -- {0}", applicationName); WriteLine("^4 Copyright 2011 Google Inc"); WriteLine(); } /// <summary> /// Displays the default "Press any key to exit" message, and waits for an user key input /// </summary> public static void PressAnyKeyToExit() { if (IsInteractive) { WriteLine(); WriteLine("^8 Press any key to exit^1"); Console.ReadKey(); } } /// <summary> /// Terminates the application. /// </summary> public static void Exit() { Console.ForegroundColor = ConsoleColor.Gray; Environment.Exit(0); } /// <summary> /// Displays the default "Press ENTER to continue" message, and waits for an user key input /// </summary> public static void PressEnterToContinue() { if (IsInteractive) { WriteLine(); WriteLine("^8 Press ENTER to continue^1"); while (Console.ReadKey().Key != ConsoleKey.Enter) {} } } /// <summary> /// Gives the user a choice of options to choose from /// </summary> /// <param name="question">The question which should be asked</param> /// <param name="choices">All possible choices</param> public static void RequestUserChoice(string question, params UserOption[] choices) { // Validate parameters question.ThrowIfNullOrEmpty("question"); choices.ThrowIfNullOrEmpty("choices"); // Show the question WriteLine(" ^9{0}", question); // Display all choices int i = 1; foreach (UserOption option in choices) { WriteLine(" ^8{0}.)^9 {1}", i++, option.Name); } WriteLine(); // Request user input UserOption choice = null; do { Write(" ^1Please pick an option: ^9"); string input = Console.ReadLine(); // Check if this is a valid choice uint num; if (uint.TryParse(input, out num) && num > 0 && choices.Length >= num) { // It is a number choice = choices[num - 1]; } else { // Check if the user typed in the keyword foreach (UserOption option in choices) { if (String.Equals(option.Name, input, StringComparison.InvariantCultureIgnoreCase)) { choice = option; break; // Valid choice } } } if (choice == null) { WriteLine(" ^6Please pick one of the options displayed above!"); } } while (choice == null); // Execute the option the user picked choice.Target(); } /// <summary> /// Gives the user a Yes/No choice and waits for his answer. /// </summary> public static bool RequestUserChoice(string question) { question.ThrowIfNull("question"); // Show the question. Write(" ^1{0} [^8{1}^1]: ^9", question, "y/n"); // Wait for the user input. char c; do { c = Console.ReadKey(true).KeyChar; } while (c != 'y' && c != 'n'); WriteLine(c.ToString()); return c == 'y'; } /// <summary> /// Enables the command line exception handling /// Prevents the application from just exiting, but tries to display helpful error message instead /// </summary> public static void EnableExceptionHandling() { AppDomain.CurrentDomain.UnhandledException += HandleUnhandledException; } private static void HandleUnhandledException(object sender, UnhandledExceptionEventArgs args) { Exception exception = args.ExceptionObject as Exception; // Display the exception WriteLine(); WriteLine(" ^6An error has occured:"); WriteLine(" ^6{0}", exception == null ? "<unknown error>" : exception.Message); // Display stacktrace if (IsInteractive) { WriteLine(); WriteLine("^8 Press any key to display the stacktrace"); Console.ReadKey(); } WriteLine(); WriteLine(" ^1{0}", exception); // Close the application PressAnyKeyToExit(); Environment.Exit(-1); } /// <summary> /// Writes the specified text to the console /// Applies special color filters (^0, ^1, ...) /// </summary> public static void Write(string format, params object[] values) { string text = String.Format(format, values); Console.ForegroundColor = ConsoleColor.Gray; // Replace ^1, ... color tags. while (text.Contains("^")) { int index = text.IndexOf("^"); // Check if a number follows the index if (index+1 < text.Length && Char.IsDigit(text[index+1])) { // Yes - it is a color notation InternalWrite(text.Substring(0, index)); // Pre-Colornotation text Console.ForegroundColor = (ConsoleColor) (text[index + 1] - '0' + 6); text = text.Substring(index + 2); // Skip the two-char notation } else { // Skip ahead InternalWrite(text.Substring(0, index)); text = text.Substring(index + 1); } } // Write the remaining text InternalWrite(text); } private static void InternalWrite(string text) { // Check for color tags. Match match; while ((match = ColorRegex.Match(text)).Success) { // Write the text before the tag. Console.Write(text.Substring(0, match.Index)); // Change the color Console.ForegroundColor = GetColor(match.Groups[1].ToString()); text = text.Substring(match.Index + match.Length); } // Write the remaining text. Console.Write(text); } private static ConsoleColor GetColor(string id) { return (ConsoleColor)Enum.Parse(typeof(ConsoleColor), id, true); } /// <summary> /// Writes the specified text to the console /// Applies special color filters (^0, ^1, ...) /// </summary> public static void WriteLine(string format, params object[] values) { Write(format+Environment.NewLine, values); } /// <summary> /// Writes an empty line into the console stream /// </summary> public static void WriteLine() { WriteLine(""); } /// <summary> /// Writes a result into the console stream. /// </summary> public static void WriteResult(string name, object value) { if (value == null) { value = "<null>"; } string strValue = value.ToString(); if (strValue.Length == 0) { strValue = "<empty>"; } WriteLine(" ^4{0}: ^9{1}", name, strValue); } /// <summary> /// Writes an action statement into the console stream. /// </summary> public static void WriteAction(string action) { WriteLine(" ^8{0}", action); } /// <summary> /// Writes an error into the console stream. /// </summary> public static void WriteError(string error, params object[] values) { WriteLine(" ^6"+error, values); } } }
zzfocuzz-deepbotcopy
SampleHelper/CommandLine.cs
C#
asf20
14,247
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; namespace Google.Apis.Samples.Helper { /// <summary> /// Extension method container class. /// </summary> public static class Extensions { /// <summary> /// Trims the string to the specified length, and replaces the end with "..." if trimmed. /// </summary> public static string TrimByLength(this string str, int maxLength) { if (maxLength < 3) { throw new ArgumentException("Please specify a maximum length of at least 3", "maxLength"); } if (str.Length <= maxLength) { return str; // Nothing to do. } return str.Substring(0, maxLength - 3) + "..."; } /// <summary> /// Formats an Exception as a HTML string. /// </summary> /// <param name="ex">The exception to format.</param> /// <returns>Formatted HTML string.</returns> public static string ToHtmlString(this Exception ex) { string str = ex.ToString(); str = str.Replace(Environment.NewLine, Environment.NewLine + "<br/>"); str = str.Replace(" ", " &nbsp;"); return string.Format("<font color=\"red\">{0}</font>", str); } /// <summary> /// Throws an ArgumentNullException if the specified object is null. /// </summary> /// <param name="toCheck">The object to check.</param> /// <param name="paramName">The name of the parameter.</param> public static void ThrowIfNull(this object toCheck, string paramName) { if (toCheck == null) { throw new ArgumentNullException(paramName); } } /// <summary> /// Throws an ArgumentNullException if the specified string is null or empty. /// </summary> /// <param name="toCheck">The object to check.</param> /// <param name="paramName">The name of the parameter.</param> public static void ThrowIfNullOrEmpty(this string toCheck, string paramName) { if (string.IsNullOrEmpty(toCheck)) { throw new ArgumentNullException(paramName); } } /// <summary> /// Throws an ArgumentNullException if the specified array is null or empty. /// </summary> /// <param name="toCheck">The object to check.</param> /// <param name="paramName">The name of the parameter.</param> public static void ThrowIfNullOrEmpty(this object[] toCheck, string paramName) { if (toCheck == null || toCheck.Length == 0) { throw new ArgumentNullException(paramName); } } } }
zzfocuzz-deepbotcopy
SampleHelper/Extensions.cs
C#
asf20
3,452
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.Windows.Forms; namespace Google.Apis.Samples.Helper { /// <summary> /// Reflection Helper /// </summary> public static class ReflectionUtils { /// <summary> /// Tries to return a descriptive name for the specified member info. /// Uses the DescriptionAttribute if available. /// </summary> /// <returns>Description from DescriptionAttriute or name of the MemberInfo</returns> public static string GetDescriptiveName(MemberInfo info) { // If available: Return the description set in the DescriptionAttribute foreach (DescriptionAttribute attribute in info.GetCustomAttributes(typeof(DescriptionAttribute), true)) { return attribute.Description; } // Otherwise: Return the name of the member return info.Name; } /// <summary> /// Selects all type members from the collection which have the specified argument. /// </summary> /// <typeparam name="TMemberInfo">The type of the member the collection is made of.</typeparam> /// <typeparam name="TAttribute">The attribute to look for.</typeparam> /// <param name="collection">The collection select from.</param> /// <returns>Only the TypeMembers which haev the specified argument defined.</returns> public static IEnumerable<KeyValuePair<TMemberInfo, TAttribute>> WithAttribute<TMemberInfo, TAttribute>( this IEnumerable<TMemberInfo> collection) where TAttribute : Attribute where TMemberInfo : MemberInfo { Type attributeType = typeof(TAttribute); return from TMemberInfo info in collection let attribute = info.GetCustomAttributes(attributeType, true).SingleOrDefault() as TAttribute where attribute != null select new KeyValuePair<TMemberInfo, TAttribute>(info, attribute); } /// <summary> /// Returns the value of the static field specified by the given name, /// or the default(T) if the field is not found. /// </summary> /// <typeparam name="T">The type of the field.</typeparam> /// <param name="type">The type containing the field.</param> /// <param name="fieldName">The name of the field.</param> /// <returns>The value of this field.</returns> public static T GetStaticField<T>(Type type, string fieldName) { var field = type.GetField(fieldName); if (field == null) { return default(T); } return (T) field.GetValue(null); } /// <summary> /// Verifies that the ClientID/ClientSecret/DeveloperKey is set in the specified class. /// </summary> /// <param name="type">ClientCredentials.cs class.</param> public static void VerifyCredentials(Type type) { var regex = new Regex("<.+>"); var errors = (from fieldName in new[] { "ClientID", "ClientSecret", "ApiKey", "BucketPath" } let field = GetStaticField<string>(type, fieldName) where field != null && regex.IsMatch(field) select "- " + fieldName + " is currently not set.").ToList(); if (errors.Count > 0) { errors.Insert(0, "Please modify the ClientCredentials.cs:"); errors.Add("You can find this information on the Google API Console."); string msg = String.Join(Environment.NewLine, errors.ToArray()); CommandLine.WriteError(msg); MessageBox.Show(msg, "Please enter your credentials!", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(0); } } } }
zzfocuzz-deepbotcopy
SampleHelper/ReflectionUtils.cs
C#
asf20
4,718
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SampleHelper")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("SampleHelper")] [assembly: AssemblyCopyright("© 2011 Google Inc")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7f1c92c1-a040-4f4a-8be4-d517d66a3c66")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
SampleHelper/Properties/AssemblyInfo.cs
C#
asf20
1,446
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System.Reflection; using System.Runtime.InteropServices; using System.Windows.Forms; namespace Google.Apis.Samples.Helper { /// <summary> /// General Utility class for samples. /// </summary> public class Util { /// <summary> /// Returns the name of the application currently being run. /// </summary> public static string ApplicationName { get { return Assembly.GetEntryAssembly().GetName().Name; } } /// <summary> /// Tries to retrieve and return the content of the clipboard. Will trim the content to the specified length. /// Removes all new line characters from the input. /// </summary> /// <remarks>Requires the STAThread attribute on the Main method.</remarks> /// <returns>Trimmed content of the clipboard, or null if unable to retrieve.</returns> public static string GetSingleLineClipboardContent(int maxLen) { try { string text = Clipboard.GetText().Replace("\r", "").Replace("\n", ""); if (text.Length > maxLen) { return text.Substring(0, maxLen); } return text; } catch (ExternalException) { return null; // Something is preventing us from getting the clipboard content -> return. } } /// <summary> /// Changes the clipboard content to the specified value. /// </summary> /// <remarks>Requires the STAThread attribute on the Main method.</remarks> /// <param name="text"></param> public static void SetClipboard(string text) { try { Clipboard.SetText(text); } catch (ExternalException) {} } } }
zzfocuzz-deepbotcopy
SampleHelper/Util.cs
C#
asf20
2,523
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; namespace Google.Apis.Samples.Helper { /// <summary> /// A choice option which can be picked by the user /// Used by the CommandLine class /// </summary> public sealed class UserOption { /// <summary> /// Creates a new option based upon the specified data /// </summary> /// <param name="name">Name to display</param> /// <param name="target">Target function to call if this option was picked</param> public UserOption(string name, Action target) { Name = name; Target = target; } /// <summary> /// Name/Keyword to display /// </summary> public string Name { get; private set; } /// <summary> /// The function which will be called if this option was picked /// </summary> public Action Target { get; private set; } } }
zzfocuzz-deepbotcopy
SampleHelper/UserOption.cs
C#
asf20
1,524
<html> <title>Google .NET Client API &ndash; GoogleApis.SampleHelper</title> <body> <h2>Instructions for the Google .NET Client API &ndash; GoogleApis.SampleHelper</h2> <p> This sample helper contains some useful methods which are shared between all samples. The code contained within here is usually not relevant for the samples themselves, but is used for nicer input/output and user interaction in general. The helper contains helper classes for: </p> <ul> <li>Colored Console I/O</li> <li>Requesting User Input</li> <li>Parsing Command-Line Arguments</li> <li>OAuth2 Token Caching (not recommended)</li> <li>Reflection</li> <li>General Utility and Extension methods</li> </ul> </body> </html>
zzfocuzz-deepbotcopy
SampleHelper/README.html
HTML
asf20
703
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Windows.Forms; namespace Google.Apis.Samples.Helper.Forms { /// <summary> /// OAuth2 authorization dialog which provides the native application authorization flow. /// </summary> public partial class OAuth2AuthorizationDialog : Form { /// <summary> /// The URI used for user-authentication. /// </summary> public Uri AuthorizationUri { get; set; } /// <summary> /// The authorization code retrieved from the user. /// </summary> public string AuthorizationCode { get; private set; } /// <summary> /// The authorization error (if any occured), or null. /// </summary> public string AuthorizationError { get; private set; } public OAuth2AuthorizationDialog() { InitializeComponent(); content.Controls.Add(new OAuth2IntroPanel()); AuthorizationCode = null; } /// <summary> /// Shows the authorization form and uses the specified URL for authorization. /// </summary> /// <returns>The authorization code.</returns> public static string ShowDialog(Uri authUri) { var dialog = new OAuth2AuthorizationDialog { AuthorizationUri = authUri }; dialog.ShowDialog(); return dialog.AuthorizationCode; } private void bCancel_Click(object sender, EventArgs e) { Close(); } private void OAuth2AuthorizationDialog_FormClosing(object sender, FormClosingEventArgs e) { if (!string.IsNullOrEmpty(AuthorizationCode) || !string.IsNullOrEmpty(AuthorizationError)) { return; // We are done here. } // Display a "Are you sure?" message box to the user. DialogResult result = MessageBox.Show( "This application cannot continue without your authorization. Are you sure you want to " + "cancel the authorization request?", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.No) { // The user doesn't want to close the form anymore. e.Cancel = true; } } private void bNext_Click(object sender, EventArgs e) { if (content.Controls[0] is OAuth2IntroPanel) { // We are on the first page. Move to the next one. content.Controls.Clear(); bNext.Enabled = false; // Disable the next button as long as no code has been entered. var nextPanel = new OAuth2CodePanel(this, AuthorizationUri); nextPanel.OnAuthorizationCodeChanged += (textBox, eventArgs) => { bNext.Enabled = !string.IsNullOrEmpty(nextPanel.AuthorizationCode); }; nextPanel.OnValidAuthorizationCode += bNext_Click; nextPanel.OnAuthorizationError += (exception, eventArgs) => OnAuthenticationError(exception as Exception); content.Controls.Add(nextPanel); } else if (content.Controls[0] is OAuth2CodePanel) { AuthorizationCode = ((OAuth2CodePanel) content.Controls[0]).AuthorizationCode; Close(); } } private void OnAuthenticationError(Exception exception) { MessageBox.Show(exception.Message, "Authentication request failed", MessageBoxButtons.OK, MessageBoxIcon.Error); AuthorizationError = exception.Message; Invoke(new Action(Close)); } } }
zzfocuzz-deepbotcopy
SampleHelper/Forms/OAuth2AuthorizationDialog.cs
C#
asf20
4,685
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Text.RegularExpressions; using System.Threading; using System.Windows.Forms; namespace Google.Apis.Samples.Helper.Forms { /// <summary> /// The second panel of the OAuth2Authorization Dialog. /// Provides the "Authorization Code" text box. /// </summary> public partial class OAuth2CodePanel : UserControl { private const string SuccessRegexPattern = "Success code=([^\\s]+)"; private const string DeniedRegexPattern = "Denied error=([^\\s]+)"; private readonly Regex deniedRegex = new Regex(DeniedRegexPattern, RegexOptions.Compiled); private readonly Regex successRegex = new Regex(SuccessRegexPattern, RegexOptions.Compiled); private bool isClosing; public OAuth2CodePanel() { InitializeComponent(); } public OAuth2CodePanel(Form owner, Uri authUri) : this() { AuthorizationUri = authUri; owner.Closed += (sender, args) => Unload(); } /// <summary> /// The authorization code entered by the user, or null/empty. /// </summary> public string AuthorizationCode { get { return textCode.Text; } } /// <summary> /// The url used for authorization. /// </summary> public Uri AuthorizationUri { get; private set; } /// <summary> /// Fired if the entered authorization code changes. /// </summary> public event EventHandler OnAuthorizationCodeChanged; /// <summary> /// Fired if a valid authorization code has been entered. Will not fire for user-entered codes. /// </summary> public event EventHandler OnValidAuthorizationCode; /// <summary> /// Fired if the authorization request failed. Sender will be an exception object. /// </summary> public event EventHandler OnAuthorizationError; private void OAuth2CodePanel_Load(object sender, EventArgs e) { var worker = new BackgroundWorker(); worker.DoWork += RunCodeGrabber; worker.RunWorkerAsync(); // Register our change event. textCode.TextChanged += (textBox, eventArgs) => { if (OnAuthorizationCodeChanged != null) { OnAuthorizationCodeChanged(textBox, eventArgs); } }; // Open the browser window. OpenRequestBrowserWindow(); } /// <summary> /// Unloads this panel. /// </summary> private void Unload() { isClosing = true; } /// <summary> /// This method looks at the process list and tries to grab the authorization code. /// </summary> private void RunCodeGrabber(object sender, DoWorkEventArgs e) { Thread.Sleep(2000); // Wait until the browser window opens. while (!isClosing) { string code = FindCodeByWindowTitle(true); if (!string.IsNullOrEmpty(code)) { // Code found. isClosing = true; Invoke( new Action( () => { // Enter the code into the textbox. textCode.Text = code; textCode.Enabled = false; if (OnValidAuthorizationCode != null) { OnValidAuthorizationCode(this, EventArgs.Empty); } FocusConsoleWindow(); })); return; } // Don't use up all the CPU time. Thread.Sleep(100); } } /// <summary> /// Retrieves the authorization code by looking at the window titles of running processes. /// </summary> /// <param name="minimizeWindow">Defines whether the window should be minimized after it has been found.</param> private string FindCodeByWindowTitle(bool minimizeWindow) { foreach (Process process in Process.GetProcesses()) { string title = process.MainWindowTitle; if (string.IsNullOrEmpty(title)) { continue; } // If we got an response, fetch the code and return it. Match match = successRegex.Match(title); if (match.Success) { string code = match.Groups[1].ToString(); if (minimizeWindow) { MinimizeWindow(process.MainWindowHandle); } return code; } // Check if we got an error response. Match errorMatch = deniedRegex.Match(title); if (errorMatch.Success) { string error = errorMatch.Groups[1].ToString(); if (minimizeWindow) { MinimizeWindow(process.MainWindowHandle); } if (OnAuthorizationError != null) { OnAuthorizationError( new AuthenticationException("Authorization request cancelled: " + error), EventArgs.Empty); } } } return null; // No authorization window was found. } /// <summary> /// Opens the authorization request browser window. /// </summary> private void OpenRequestBrowserWindow() { // Let the operation system choose the right browser. ThreadPool.QueueUserWorkItem((obj) => Process.Start(AuthorizationUri.ToString())); } private void bBrowser_Click(object sender, EventArgs e) { OpenRequestBrowserWindow(); } #region Eye-Candy [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hWnd, ShowWindowCommands nCmdShow); protected virtual void FocusConsoleWindow() { // Catch exceptions as chances are high that this operation will fail, // and as it is basically just for eye-candy. try { Application.DoEvents(); SetForegroundWindow(Process.GetCurrentProcess().MainWindowHandle); } catch (InvalidOperationException) { } catch (BadImageFormatException) { } } protected virtual void MinimizeWindow(IntPtr hWnd) { // Catch exceptions as chances are high that this operation will fail, // and as it is basically just for eye-candy. try { Application.DoEvents(); ShowWindow(hWnd, ShowWindowCommands.ForceMinimized); } catch (InvalidOperationException) { } catch (BadImageFormatException) { } } /// <summary>Enumeration of the different ways of showing a window using /// ShowWindow</summary> private enum ShowWindowCommands : uint { /// <summary>Hides the window and activates another window.</summary> /// <remarks>See SW_HIDE</remarks> Hide = 0, /// <summary>Activates and displays a window. If the window is minimized /// or maximized, the system restores it to its original size and /// position. An application should specify this flag when displaying /// the window for the first time.</summary> /// <remarks>See SW_SHOWNORMAL</remarks> ShowNormal = 1, /// <summary>Activates the window and displays it as a minimized window.</summary> /// <remarks>See SW_SHOWMINIMIZED</remarks> ShowMinimized = 2, /// <summary>Minimizes the specified window and activates the next /// top-level window in the Z order.</summary> /// <remarks>See SW_MINIMIZE</remarks> Minimize = 6, /// <summary>Displays the window as a minimized window. This value is /// similar to "ShowMinimized", except the window is not activated.</summary> /// <remarks>See SW_SHOWMINNOACTIVE</remarks> ShowMinNoActivate = 7, ForceMinimized = 11 } #endregion } }
zzfocuzz-deepbotcopy
SampleHelper/Forms/OAuth2CodePanel.cs
C#
asf20
10,074
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System.Windows.Forms; namespace Google.Apis.Samples.Helper.Forms { /// <summary> /// The first panel of the OAuth2Authorization Dialog. /// Provides general information about the authorization process. /// </summary> public partial class OAuth2IntroPanel : UserControl { public OAuth2IntroPanel() { InitializeComponent(); } } }
zzfocuzz-deepbotcopy
SampleHelper/Forms/OAuth2IntroPanel.cs
C#
asf20
991
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using DotNetOpenAuth.OAuth2; namespace Google.Apis.Samples.Helper.NativeAuthorizationFlows { /// <summary> /// An authorization flow is the process of obtaining an AuthorizationCode /// when provided with an IAuthorizationState. /// </summary> internal interface INativeAuthorizationFlow { /// <summary> /// Retrieves the authorization of the user for the given AuthorizationState. /// </summary> /// <param name="client">The client used for authentication.</param> /// <param name="authorizationState">The state requested.</param> /// <returns>The authorization code, or null if the user cancelled the request.</returns> /// <exception cref="NotSupportedException">Thrown if this flow is not supported.</exception> string RetrieveAuthorization(UserAgentClient client, IAuthorizationState authorizationState); } }
zzfocuzz-deepbotcopy
SampleHelper/NativeAuthorizationFlows/INativeAuthorizationFlow.cs
C#
asf20
1,519
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Windows.Forms; using DotNetOpenAuth.OAuth2; using Google.Apis.Samples.Helper.Forms; namespace Google.Apis.Samples.Helper.NativeAuthorizationFlows { /// <summary> /// Describes a flow which captures the authorization code out of the window title of the browser. /// </summary> /// <remarks>Works on Windows, but not on Unix. Will failback to copy/paste mode if unsupported.</remarks> internal class WindowTitleNativeAuthorizationFlow : INativeAuthorizationFlow { private const string OutOfBandCallback = "urn:ietf:wg:oauth:2.0:oob"; public string RetrieveAuthorization(UserAgentClient client, IAuthorizationState authorizationState) { // Create the Url. authorizationState.Callback = new Uri(OutOfBandCallback); Uri url = client.RequestUserAuthorization(authorizationState); // Show the dialog. if (!Application.RenderWithVisualStyles) { Application.EnableVisualStyles(); } Application.DoEvents(); string authCode = OAuth2AuthorizationDialog.ShowDialog(url); Application.DoEvents(); if (string.IsNullOrEmpty(authCode)) { return null; // User cancelled the request. } return authCode; } } }
zzfocuzz-deepbotcopy
SampleHelper/NativeAuthorizationFlows/WindowTitleNativeAuthorizationFlow.cs
C#
asf20
1,998
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using DotNetOpenAuth.OAuth2; using Google.Apis.Samples.Helper.Properties; namespace Google.Apis.Samples.Helper.NativeAuthorizationFlows { /// <summary> /// A native authorization flow which uses a listening local loopback socket to fetch the authorization code. /// </summary> /// <remarks>Might not work if blocked by the system firewall.</remarks> public class LoopbackServerAuthorizationFlow : INativeAuthorizationFlow { private const string LoopbackCallback = "http://localhost:{0}/{1}/authorize/"; /// <summary> /// Returns a random, unused port. /// </summary> private static int GetRandomUnusedPort() { var listener = new TcpListener(IPAddress.Loopback, 0); try { listener.Start(); return ((IPEndPoint)listener.LocalEndpoint).Port; } finally { listener.Stop(); } } /// <summary> /// Handles an incoming WebRequest. /// </summary> /// <param name="context">The request to handle.</param> /// <param name="appName">Name of the application handling the request.</param> /// <returns>The authorization code, or null if the process was cancelled.</returns> private string HandleRequest(HttpListenerContext context) { try { // Check whether we got a successful response: string code = context.Request.QueryString["code"]; if (!string.IsNullOrEmpty(code)) { return code; } // Check whether we got an error response: string error = context.Request.QueryString["error"]; if (!string.IsNullOrEmpty(error)) { return null; // Request cancelled by user. } // The response is unknown to us. Choose a different authentication flow. throw new NotSupportedException( "Received an unknown response: " + Environment.NewLine + context.Request.RawUrl); } finally { // Write a response. using (var writer = new StreamWriter(context.Response.OutputStream)) { string response = Resources.LoopbackServerHtmlResponse.Replace("{APP}", Util.ApplicationName); writer.WriteLine(response); writer.Flush(); } context.Response.OutputStream.Close(); context.Response.Close(); } } public string RetrieveAuthorization(UserAgentClient client, IAuthorizationState authorizationState) { if (!HttpListener.IsSupported) { throw new NotSupportedException("HttpListener is not supported by this platform."); } // Create a HttpListener for the specified url. string url = string.Format(LoopbackCallback, GetRandomUnusedPort(), Util.ApplicationName); authorizationState.Callback = new Uri(url); var webserver = new HttpListener(); webserver.Prefixes.Add(url); // Retrieve the authorization url. Uri authUrl = client.RequestUserAuthorization(authorizationState); try { // Start the webserver. webserver.Start(); // Open the browser. Process.Start(authUrl.ToString()); // Wait for the incoming connection, then handle the request. return HandleRequest(webserver.GetContext()); } catch (HttpListenerException ex) { throw new NotSupportedException("The HttpListener threw an exception.", ex); } finally { // Stop the server after handling the one request. webserver.Stop(); } } } }
zzfocuzz-deepbotcopy
SampleHelper/NativeAuthorizationFlows/LoopbackServerAuthorizationFlow.cs
C#
asf20
4,950
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; namespace Google.Apis.Samples.Helper { /// <summary> /// Support for parsing command line flags. /// </summary> public class CommandLineFlags { private static readonly Regex ArgumentRegex = new Regex( "^-[-]?([^-][^=]*)(=(.*))?$", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary> /// Parses the specified command line arguments into the specified class. /// </summary> /// <typeparam name="T">Class where the command line arguments are stored.</typeparam> /// <param name="configuration">Class which stores the command line arguments.</param> /// <param name="args">Command line arguments.</param> /// <returns>Array of unresolved arguments.</returns> public static string[] ParseArguments<T>(T configuration, params string[] args) { const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance; List<KeyValuePair<PropertyInfo, ArgumentAttribute>> properties = typeof(T).GetProperties(flags).WithAttribute<PropertyInfo, ArgumentAttribute>().ToList(); var unresolvedArguments = new List<string>(); foreach (string arg in args) { // Parse the argument. Match match = ArgumentRegex.Match(arg); if (!match.Success) // This is not a typed argument. { unresolvedArguments.Add(arg); continue; } // Extract the argument details. bool isShortname = !arg.StartsWith("--"); string name = match.Groups[1].ToString(); string value = match.Groups[2].Length > 0 ? match.Groups[2].ToString().Substring(1) : null; // Find the argument. const StringComparison ignoreCase = StringComparison.InvariantCultureIgnoreCase; PropertyInfo property = (from kv in properties where name.Equals(isShortname ? kv.Value.ShortName : kv.Value.Name, ignoreCase) select kv.Key).SingleOrDefault(); // Check if this is a special argument we should handle. if (name == "help") { foreach (string line in GenerateCommandLineHelp(configuration)) { CommandLine.WriteAction(line); } if (property == null) { // If this isn't handled seperately, close this application. CommandLine.Exit(); return null; } } else if (name == "non-interactive") { CommandLine.IsInteractive = false; continue; } else if (property == null) { CommandLine.WriteError("Unknown argument: " + (isShortname ? "-" : "--") + name); continue; } // Change the property. object convertedValue = null; if (value == null) { if (property.PropertyType == typeof(bool)) { convertedValue = true; } } else { convertedValue = Convert.ChangeType(value, property.PropertyType); } if (convertedValue == null) { CommandLine.WriteError( string.Format( "Argument '{0}' requires a value of the type '{1}'.", name, property.PropertyType.Name)); continue; } property.SetValue(configuration, convertedValue, null); } return unresolvedArguments.ToArray(); } /// <summary> /// Generates the commandline argument help for a specified type. /// </summary> /// <typeparam name="T">Configuration.</typeparam> public static IEnumerable<string> GenerateCommandLineHelp<T>(T configuration) { const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance; List<KeyValuePair<PropertyInfo, ArgumentAttribute>> properties = typeof(T).GetProperties(flags).WithAttribute<PropertyInfo, ArgumentAttribute>().ToList(); var query = from kv in properties orderby kv.Value.Name // Group the sorted arguments by their category. group kv by kv.Value.Category into g orderby g.Key select g; // Go through each category and list all the arguments. yield return "Arguments:"; foreach (var category in query) { if (!string.IsNullOrEmpty(category.Key)) { yield return " " + category.Key; } foreach (KeyValuePair<PropertyInfo, ArgumentAttribute> pair in category) { PropertyInfo info = pair.Key; object value = info.GetValue(configuration, null); yield return " " + FormatCommandLineHelp(pair.Value, info.PropertyType, value); } yield return ""; } } /// <summary> /// Generates a single command line help for the specified argument /// Example: /// -s, --source=[Something] Sets the source of ... /// </summary> private static string FormatCommandLineHelp(ArgumentAttribute attribute, Type propertyType, object value) { // Generate the list of keywords ("-s, --source"). var keywords = new List<string>(2); if (!string.IsNullOrEmpty(attribute.ShortName)) { keywords.Add("-" + attribute.ShortName); } keywords.Add("--" + attribute.Name); string joinedKeywords = keywords.Aggregate((a, b) => a + ", " + b); // Add the assignment-tag, if applicable. string assignment = ""; if (propertyType != typeof(bool)) { assignment = string.Format("=[^1{0}^9]", (value == null) ? ".." : value.ToString()); } // Create the joined left half, and return the full string. string left = (joinedKeywords + assignment).PadRight(20); return string.Format("^9{0} ^1{1}", left, attribute.Description); } } /// <summary> /// Defines the command line argument structure of a property. /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class ArgumentAttribute : Attribute { private readonly string name; /// <summary> /// The full name of this command line argument, e.g. "source-directory". /// </summary> public string Name { get { return name; } } /// <summary> /// The short name of this command line argument, e.g. "src". Optional. /// </summary> public string ShortName { get; set; } /// <summary> /// The description of this command line argument, e.g. "The directory to fetch the data from". Optional. /// </summary> public string Description { get; set; } /// <summary> /// The category to which this argument belongs, e.g. "I/O flags". Optional. /// </summary> public string Category { get; set; } /// <summary> /// Defines the command line argument structure of a property. /// </summary> public ArgumentAttribute(string name) { this.name = name; } } }
zzfocuzz-deepbotcopy
SampleHelper/CommandLineFlags.cs
C#
asf20
8,996
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Security.Cryptography; using System.Text; namespace Google.Apis.Samples.Helper { /// <summary> /// This class is for use of samples only, on first use this class prompts the user for /// ApiKey and optionaly ClientId and ClientSecret, these are stored encrypted in a file. /// This is not sutible for production use as the user can access these keys. /// </summary> public static class PromptingClientCredentials { private static bool firstRun = true; private const string ApplicationFolderName = "Google.Apis.Samples"; private const string ClientCredentialsFileName = "client.dat"; private const string FileKeyApiKey = "ProtectedApiKey"; private const string FileKeyClientId = "ProtectedClientId"; private const string FileKeyClientSecret = "ProtectedClientSecret"; // Random data used to make this encryption key different from other information encyrpted with ProtectedData // This does not make it hard to decrypt just adds another small step. private static readonly byte[] entropy = new byte[] { 150, 116, 112, 35, 243, 210, 144, 9, 188, 122, 157, 253, 124, 115, 87, 51, 84, 178, 43, 176, 239, 198, 198, 249, 116, 190, 61, 129, 238, 23, 250, 163, 59, 26, 139 }; private const string PromptCreate = "This looks like the first time your running the Google(tm) API " + "Samples if you have already got your API key please enter it here (you can find your key " + "at https://code.google.com/apis/console/#:access). Otherwise " + "please follow the instructions at http://code.google.com/p/google-api-dotnet-client/wiki/GettingStarted " + " look out for the API Console section. " + "This will be stored encrypted on the hard drive so that only this user can access these keys."; private const string PromptSimpleCreate = PromptCreate + " For the sample you are running you need just need API Key."; private const string PromptFullCreate = PromptCreate + " For the sample you are running you need both an API Key and " + "a Client ID for installed applications."; private const string PromptFullExtend = "Another sample? Cool! This one requires ClientId for Installed applications " + " as well as the API Key you entered earlier. You can pick up your new ClientId from " + "https://code.google.com/apis/console/#:access"; /// <summary>Gives a fileInfo pointing to the CredentialsFile, creating directories if required.</summary> private static FileInfo CredentialsFile { get { string applicationDate = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); string googleAppDirectory = Path.Combine(applicationDate, ApplicationFolderName); var directoryInfo = new DirectoryInfo(googleAppDirectory); if (directoryInfo.Exists == false) { directoryInfo.Create(); } return new FileInfo(Path.Combine(googleAppDirectory, ClientCredentialsFileName)); } } /// <summary> /// Returns a IDictionary of keys and values from the CredentialsFile which is expected to be of the form /// <example> /// key=value /// key2=value2 /// </example> /// </summary> private static IDictionary<string, string> ParseFile() { var parsedValues = new Dictionary<string, string>(5); using (StreamReader sr = CredentialsFile.OpenText()) { string currentLine = sr.ReadLine(); while (currentLine != null) { int firstEquals = currentLine.IndexOf('='); if (firstEquals > 0 && firstEquals + 1 < currentLine.Length) { string key = currentLine.Substring(0, firstEquals); string value = currentLine.Substring(firstEquals + 1); parsedValues.Add(key, value); } currentLine = sr.ReadLine(); } } return parsedValues; } /// <summary> /// By prompting the user this constructs <code>SimpleClientCredentials</code> and stores them in the /// <code>CredentialsFile</code> /// </summary> private static SimpleClientCredentials CreateSimpleClientCredentials() { CommandLine.WriteLine(PromptSimpleCreate); SimpleClientCredentials simpleCredentials = CommandLine.CreateClassFromUserinput<SimpleClientCredentials>(); using (FileStream fStream = CredentialsFile.OpenWrite()) { using (TextWriter tw = new StreamWriter(fStream)) { tw.WriteLine("{0}={1}", FileKeyApiKey, Protect(simpleCredentials.ApiKey)); } } return simpleCredentials; } /// <summary> /// By prompting the user this constructs <code>FullClientCredentials</code> and stores them in the /// <code>CredentialsFile</code> /// </summary> private static FullClientCredentials CreateFullClientCredentials(bool isExtension) { CommandLine.WriteLine(isExtension ? PromptFullExtend : PromptFullCreate); FullClientCredentials fullCredentials = CommandLine.CreateClassFromUserinput<FullClientCredentials>(); using (FileStream fStream = CredentialsFile.OpenWrite()) { using (TextWriter tw = new StreamWriter(fStream)) { tw.WriteLine("{0}={1}", FileKeyApiKey, Protect(fullCredentials.ApiKey)); tw.WriteLine("{0}={1}", FileKeyClientId, Protect(fullCredentials.ClientId)); tw.WriteLine("{0}={1}", FileKeyClientSecret, Protect(fullCredentials.ClientSecret)); } } return fullCredentials; } /// <summary> /// Encrypts the clearText using the current users key, this prevents other users being able to read this /// but does not stop the current user from reading this. /// </summary> private static string Protect(string clearText) { byte[] encryptedData = ProtectedData.Protect( Encoding.ASCII.GetBytes(clearText), entropy, DataProtectionScope.CurrentUser); return Convert.ToBase64String(encryptedData); } /// <summary> /// The inverse of <code>Protect</code> this decrypts the passed-in string. /// </summary> private static string Unprotect(string encrypted) { byte[] encryptedData = Convert.FromBase64String(encrypted); byte[] clearText = ProtectedData.Unprotect(encryptedData, entropy, DataProtectionScope.CurrentUser); return Encoding.ASCII.GetString(clearText); } private static void PromptForReuse() { if ((!firstRun) || (!CredentialsFile.Exists)) { return; } firstRun = false; CommandLine.RequestUserChoice( "There are stored API Keys on this computer do you wish to use these or enter new credentials?", new UserOption("Reuse existing API Keys", () => { ;}), new UserOption("Enter new credentials", ClearClientCredentials)); } /// <summary> /// Fetches the users ApiKey either from local disk or prompts the user in the command line. /// </summary> public static SimpleClientCredentials EnsureSimpleClientCredentials() { PromptForReuse(); if (CredentialsFile.Exists == false) { return CreateSimpleClientCredentials(); } IDictionary<string, string> values = ParseFile(); if (values.ContainsKey(FileKeyApiKey) == false) { return CreateSimpleClientCredentials(); } return new SimpleClientCredentials() { ApiKey = Unprotect(values[FileKeyApiKey]) }; } /// <summary> /// Fetches the users ApiKey, ClientId and ClientSecreat either from local disk or /// prompts the user in the command line. /// </summary> public static FullClientCredentials EnsureFullClientCredentials() { PromptForReuse(); if (CredentialsFile.Exists == false) { return CreateFullClientCredentials(false); } IDictionary<string, string> values = ParseFile(); if (values.ContainsKey(FileKeyApiKey) == false || values.ContainsKey(FileKeyClientId) == false || values.ContainsKey(FileKeyClientSecret) == false) { return CreateFullClientCredentials(true); } return new FullClientCredentials() { ApiKey = Unprotect(values[FileKeyApiKey]), ClientId = Unprotect(values[FileKeyClientId]), ClientSecret = Unprotect(values[FileKeyClientSecret])}; } /// <summary> /// Removes the stored credentials from this computer /// </summary> public static void ClearClientCredentials() { FileInfo clientCredentials = CredentialsFile; if (clientCredentials.Exists) { clientCredentials.Delete(); } } } /// <summary>Simple DTO holding all the credentials required to work with the Google Api</summary> public class FullClientCredentials : SimpleClientCredentials { [Description("Client ID as shown in the 'Client ID for installed applications' section")] public string ClientId; [Description("Client secret as shown in the 'Client ID for installed applications' section")] public string ClientSecret; } /// <summary>Simple DTO holding a minimal set of credentials required to work with the Google Api</summary> public class SimpleClientCredentials { [Description("API key as shown in the Simple API Access section.")] public string ApiKey; } }
zzfocuzz-deepbotcopy
SampleHelper/PromptingClientCredentials.cs
C#
asf20
11,503
Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("Calendar.VB.ConsoleApp")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("Google")> <Assembly: AssemblyProduct("Calendar.VB.ConsoleApp")> <Assembly: AssemblyCopyright("Copyright © Google 2013")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("72b4cdb2-a015-4731-8d87-304369908274")> ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")>
zzfocuzz-deepbotcopy
Calendar.VB.ConsoleApp/My Project/AssemblyInfo.vb
Visual Basic .NET
asf20
1,210
'Copyright 2013 Google Inc 'Licensed under the Apache License, Version 2.0(the "License"); 'you may not use this file except in compliance with the License. 'You may obtain a copy of the License at ' http://www.apache.org/licenses/LICENSE-2.0 'Unless required by applicable law or agreed to in writing, software 'distributed under the License is distributed on an "AS IS" BASIS, 'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 'See the License for the specific language governing permissions and 'limitations under the License. Imports System.Collections.Generic Imports DotNetOpenAuth.OAuth2 Imports Google.Apis.Authentication.OAuth2 Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth Imports Google.Apis.Calendar.v3 Imports Google.Apis.Calendar.v3.Data Imports Google.Apis.Calendar.v3.EventsResource Imports Google.Apis.Samples.Helper Imports Google.Apis.Services Imports Google.Apis.Util ''' <summary> ''' An sample for the Calendar API which displays a list of calendars and events in the first calendar. ''' https://developers.google.com/google-apps/calendar/ ''' </summary> Module Program '' Calendar scopes which is initialized on the main method Dim scopes As IList(Of String) = New List(Of String)() '' Calendar service Dim service As CalendarService Sub Main() ' Add the calendar specific scope to the scopes list scopes.Add(CalendarService.Scopes.Calendar.GetStringValue()) ' Display the header and initialize the sample CommandLine.EnableExceptionHandling() CommandLine.DisplayGoogleSampleHeader("Google.Api.Calendar.v3 Sample") ' Create the authenticator Dim credentials As FullClientCredentials = PromptingClientCredentials.EnsureFullClientCredentials() Dim provider = New NativeApplicationClient(GoogleAuthenticationServer.Description) provider.ClientIdentifier = credentials.ClientId provider.ClientSecret = credentials.ClientSecret Dim auth As New OAuth2Authenticator(Of NativeApplicationClient)(provider, AddressOf GetAuthorization) ' Create the calendar service using an initializer instance Dim initializer As New BaseClientService.Initializer() initializer.Authenticator = auth service = New CalendarService(initializer) ' Fetch the list of calendar list Dim list As IList(Of CalendarListEntry) = service.CalendarList.List().Execute().Items() ' Display all calendars DisplayList(list) For Each calendar As Data.CalendarListEntry In list ' Display calendar's events DisplayFirstCalendarEvents(calendar) Next CommandLine.PressAnyKeyToExit() End Sub Function GetAuthorization(client As NativeApplicationClient) As IAuthorizationState ' You should use a more secure way of storing the key here as ' .NET applications can be disassembled using a reflection tool. Const STORAGE As String = "google.samples.dotnet.calendar" Const KEY As String = "s0mekey" ' Check if there is a cached refresh token available. Dim state As IAuthorizationState = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY) If Not state Is Nothing Then Try client.RefreshToken(state) Return state ' we are done Catch ex As DotNetOpenAuth.Messaging.ProtocolException CommandLine.WriteError("Using an existing refresh token failed: " + ex.Message) CommandLine.WriteLine() End Try End If ' Retrieve the authorization from the user state = AuthorizationMgr.RequestNativeAuthorization(client, scopes.ToArray()) AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state) Return state End Function ''' <summary>Displays all calendars.</summary> Private Sub DisplayList(list As IList(Of CalendarListEntry)) CommandLine.WriteLine("Lists of calendars:") For Each item As CalendarListEntry In list CommandLine.WriteResult(item.Summary, "Location: " & item.Location & ", TimeZone: " & item.TimeZone) Next End Sub ''' <summary>Displays the calendar's events.</summary> Private Sub DisplayFirstCalendarEvents(list As CalendarListEntry) CommandLine.WriteLine(Environment.NewLine & "Maximum 5 first events from {0}:", list.Summary) Dim requeust As ListRequest = service.Events.List(list.Id) ' Set MaxResults and TimeMin with sample values requeust.MaxResults = 5 requeust.TimeMin = "2012-01-01T00:00:00-00:00" ' Fetch the list of events For Each calendarEvent As Data.Event In requeust.Execute().Items Dim startDate As String = "Unspecified" If (Not calendarEvent.Start Is Nothing) Then If (Not calendarEvent.Start.Date Is Nothing) Then startDate = calendarEvent.Start.Date.ToString() End If End If CommandLine.WriteResult(calendarEvent.Summary, "Start at: " & startDate) Next End Sub End Module
zzfocuzz-deepbotcopy
Calendar.VB.ConsoleApp/Program.vb
Visual Basic .NET
asf20
5,307
<html> <title>Google .NET Client API &ndash; Calendar.VB.ConsoleApp</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Calendar.VB.ConsoleApp</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FCalendar.VB.ConsoleApp">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Calendar.VB.ConsoleApp/Program.vb?repo=samples">Program.vb</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Tasks API for your project </li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Calendar.VB.ConsoleApp\bin\Debug</i></li> </ul> </body> </html>
zzfocuzz-deepbotcopy
Calendar.VB.ConsoleApp/README.html
HTML
asf20
1,480
/* Copyright 2013 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using Google.Apis.Adsense.v1_3; using Google.Apis.Adsense.v1_3.Data; using Google.Apis.Samples.Helper; using Google.Apis.Util; namespace AdSense.Sample { /// <summary> /// A sample consumer that runs multiple requests against the AdSense Management API. /// These include: /// <list type="bullet"> /// <item> /// <description>Retrieves the list of accounts</description> /// </item> /// <item> /// <description>Retrieves the list of ad clients</description> /// </item> /// <item> /// <description>Retrieves the list of ad units for a random ad client</description> /// </item> /// <item> /// <description>Retrieves the list of custom channels for a random ad unit</description> /// </item> /// <item> /// <description>Retrieves the list of custom channels</description> /// </item> /// <item> /// <description>Retrieves the list of ad units tagged by a random custom channel</description> /// </item> /// <item> /// <description>Retrieves the list of URL channels for the logged in user</description> /// </item> /// <item> /// <description>Retrieves the list of saved ad styles for the logged in user</description> /// </item> /// <item> /// <description>Retrieves the list of saved reports for the logged in user</description> /// </item> /// <item> /// <description>Generates a random saved report</description> /// </item> /// <item> /// <description>Generates a saved report</description> /// </item> /// <item> /// <description>Generates a saved report with paging</description> /// </item> /// </list> /// </summary> public class ManagementApiConsumer { private static readonly string DateFormat = "yyyy-MM-dd"; private AdSenseService service; private int maxListPageSize; /// <summary> /// Initializes a new instance of the <see cref="ManagementApiConsumer"/> class. /// </summary> /// <param name="service">AdSense service object on which to run the requests.</param> /// <param name="maxListPageSize">The maximum page size to retrieve.</param> public ManagementApiConsumer(AdSenseService service, int maxListPageSize) { this.service = service; this.maxListPageSize = maxListPageSize; } /// <summary> /// Runs multiple Publisher requests against the AdSense Management API. /// </summary> internal void RunCalls() { Accounts accounts = GetAllAccounts(); // Get an example account, so we can run the following samples. var exampleAccount = accounts.Items.NullToEmpty().FirstOrDefault(); if (exampleAccount != null) { DisplayAccountTree(exampleAccount.Id); DisplayAllAdClientsForAccount(exampleAccount.Id); } var adClients = GetAllAdClients(); // Get an ad client, so we can run the rest of the samples. var exampleAdClient = adClients.Items.NullToEmpty().FirstOrDefault(); if (exampleAdClient != null) { var adUnits = GetAllAdUnits(exampleAdClient.Id); // Get an example ad unit, so we can run the following sample. var exampleAdUnit = adUnits.Items.NullToEmpty().FirstOrDefault(); if (exampleAdUnit != null) { DisplayAllCustomChannelsForAdUnit(exampleAdClient.Id, exampleAdUnit.Id); } var customChannels = GetAllCustomChannels(exampleAdClient.Id); // Get an example custom channel, so we can run the following sample. var exampleCustomChannel = customChannels.Items.NullToEmpty().FirstOrDefault(); if (exampleCustomChannel != null) { DisplayAllAdUnits(exampleAdClient.Id, exampleCustomChannel.Id); } DisplayAllUrlChannels(exampleAdClient.Id); DisplayAllSavedAdStyles(); SavedReports savedReports = GetAllSavedReports(); // Get an example saved report, so we can run the following sample. var exampleSavedReport = savedReports.Items.NullToEmpty().FirstOrDefault(); if (exampleSavedReport != null) { GenerateSavedReport(exampleSavedReport.Id); } GenerateReport(exampleAdClient.Id); GenerateReportWithPaging(exampleAdClient.Id); } DisplayAllMetricsAndDimensions(); DisplayAllAlerts(); CommandLine.PressAnyKeyToExit(); } /// <summary> /// Gets and prints all accounts for the logged in user. /// </summary> /// <returns>The last page of retrieved accounts.</returns> private Accounts GetAllAccounts() { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all AdSense accounts"); CommandLine.WriteLine("================================================================="); // Retrieve account list in pages and display data as we receive it. string pageToken = null; Accounts accountResponse = null; do { var accountRequest = this.service.Accounts.List(); accountRequest.MaxResults = this.maxListPageSize; accountRequest.PageToken = pageToken; accountResponse = accountRequest.Execute(); if (accountResponse.Items.IsNotNullOrEmpty()) { foreach (var account in accountResponse.Items) { CommandLine.WriteLine( "Account with ID \"{0}\" and name \"{1}\" was found.", account.Id, account.Name); } } else { CommandLine.WriteLine("No accounts found."); } pageToken = accountResponse.NextPageToken; } while (pageToken != null); CommandLine.WriteLine(); // Return the last page of accounts, so that the main sample has something to run. return accountResponse; } /// <summary> /// Displays the AdSense account tree for a given account. /// </summary> /// <param name="accountId">The ID for the account to be used.</param> private void DisplayAccountTree(string accountId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Displaying AdSense account tree for {0}", accountId); CommandLine.WriteLine("================================================================="); // Retrieve account. var account = this.service.Accounts.Get(accountId).Execute(); this.DisplayTree(account, 0); CommandLine.WriteLine(); } /// <summary> /// Auxiliary method to recurse through the account tree, displaying it. /// </summary> /// <param name="parentAccount">The account to print a sub-tree for.</param> /// <param name="level">The depth at which the top account exists in the tree.</param> private void DisplayTree(Account parentAccount, int level) { CommandLine.WriteLine( "{0}Account with ID \"{1}\" and name \"{2}\" was found.", new string(' ', 2 * level), parentAccount.Id, parentAccount.Name); foreach (var subAccount in parentAccount.SubAccounts.NullToEmpty()) { DisplayTree(subAccount, level + 1); } } /// <summary> /// Displays all ad clients for an account. /// </summary> /// <param name="accountId">The ID for the account to be used.</param> private void DisplayAllAdClientsForAccount(string accountId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all ad clients for account {0}", accountId); CommandLine.WriteLine("================================================================="); // Retrieve ad client list in pages and display data as we receive it. string pageToken = null; AdClients adClientResponse = null; do { var adClientRequest = this.service.Accounts.Adclients.List(accountId); adClientRequest.MaxResults = this.maxListPageSize; adClientRequest.PageToken = pageToken; adClientResponse = adClientRequest.Execute(); if (adClientResponse.Items.IsNotNullOrEmpty()) { foreach (var adClient in adClientResponse.Items) { CommandLine.WriteLine( "Ad client for product \"{0}\" with ID \"{1}\" was found.", adClient.ProductCode, adClient.Id); CommandLine.WriteLine( "\tSupports reporting: {0}", adClient.SupportsReporting.Value ? "Yes" : "No"); } } else { CommandLine.WriteLine("No ad clients found."); } pageToken = adClientResponse.NextPageToken; } while (pageToken != null); CommandLine.WriteLine(); } /// <summary> /// Gets and prints all ad clients for the logged in user's default account. /// </summary> /// <returns>The last page of retrieved accounts.</returns> private AdClients GetAllAdClients() { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all ad clients for default account"); CommandLine.WriteLine("================================================================="); // Retrieve ad client list in pages and display data as we receive it. string pageToken = null; AdClients adClientResponse = null; do { var adClientRequest = this.service.Adclients.List(); adClientRequest.MaxResults = this.maxListPageSize; adClientRequest.PageToken = pageToken; adClientResponse = adClientRequest.Execute(); if (adClientResponse.Items.IsNotNullOrEmpty()) { foreach (var adClient in adClientResponse.Items) { CommandLine.WriteLine( "Ad client for product \"{0}\" with ID \"{1}\" was found.", adClient.ProductCode, adClient.Id); CommandLine.WriteLine( "\tSupports reporting: {0}", adClient.SupportsReporting.Value ? "Yes" : "No"); } } else { CommandLine.WriteLine("No ad clients found."); } pageToken = adClientResponse.NextPageToken; } while (pageToken != null); CommandLine.WriteLine(); // Return the last page of ad clients, so that the main sample has something to run. return adClientResponse; } /// <summary> /// Gets and prints all ad units in an ad client. /// </summary> /// <param name="adClientId">The ID for the ad client to be used.</param> /// <returns>The last page of retrieved accounts.</returns> private AdUnits GetAllAdUnits(string adClientId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all ad units for ad client {0}", adClientId); CommandLine.WriteLine("================================================================="); // Retrieve ad client list in pages and display data as we receive it. string pageToken = null; AdUnits adUnitResponse = null; do { var adUnitRequest = this.service.Adunits.List(adClientId); adUnitRequest.MaxResults = this.maxListPageSize; adUnitRequest.PageToken = pageToken; adUnitResponse = adUnitRequest.Execute(); if (adUnitResponse.Items.IsNotNullOrEmpty()) { foreach (var adUnit in adUnitResponse.Items) { CommandLine.WriteLine( "Ad unit with code \"{0}\", name \"{1}\" and status \"{2}\" " + "was found.", adUnit.Code, adUnit.Name, adUnit.Status); } } else { CommandLine.WriteLine("No ad units found."); } pageToken = adUnitResponse.NextPageToken; } while (pageToken != null); CommandLine.WriteLine(); // Return the last page of ad units, so that the main sample has something to run. return adUnitResponse; } /// <summary> /// Gets and prints all custom channels in an ad client. /// </summary> /// <param name="adClientId">The ID for the ad client to be used.</param> /// <returns>The last page of custom channels.</returns> private CustomChannels GetAllCustomChannels(string adClientId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all custom channels for ad client {0}", adClientId); CommandLine.WriteLine("================================================================="); // Retrieve custom channel list in pages and display data as we receive it. string pageToken = null; CustomChannels customChannelResponse = null; do { var customChannelRequest = this.service.Customchannels.List(adClientId); customChannelRequest.MaxResults = this.maxListPageSize; customChannelRequest.PageToken = pageToken; customChannelResponse = customChannelRequest.Execute(); if (customChannelResponse.Items.IsNotNullOrEmpty()) { foreach (var customChannel in customChannelResponse.Items) { CommandLine.WriteLine( "Custom channel with code \"{0}\" and name \"{1}\" was found.", customChannel.Code, customChannel.Name); } } else { CommandLine.WriteLine("No custom channels found."); } pageToken = customChannelResponse.NextPageToken; } while (pageToken != null); CommandLine.WriteLine(); // Return the last page of custom channels, so that the main sample has something to run. return customChannelResponse; } /// <summary> /// Prints all ad units corresponding to a specified custom channel. /// </summary> /// <param name="adClientId">The ID for the ad client to be used.</param> /// <param name="customChannelId">The ID for the custom channel to be used.</param> private void DisplayAllAdUnits(string adClientId, string customChannelId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all ad units for custom channel {0}", customChannelId); CommandLine.WriteLine("================================================================="); // Retrieve ad client list in pages and display data as we receive it. string pageToken = null; AdUnits adUnitResponse = null; do { var adUnitRequest = this.service.Customchannels.Adunits.List(adClientId, customChannelId); adUnitRequest.MaxResults = this.maxListPageSize; adUnitRequest.PageToken = pageToken; adUnitResponse = adUnitRequest.Execute(); if (adUnitResponse.Items.IsNotNullOrEmpty()) { foreach (var adUnit in adUnitResponse.Items) { CommandLine.WriteLine( "Ad unit with code \"{0}\", name \"{1}\" and status \"{2}\" " + "was found.", adUnit.Code, adUnit.Name, adUnit.Status); } } else { CommandLine.WriteLine("No ad units found."); } pageToken = adUnitResponse.NextPageToken; } while (pageToken != null); CommandLine.WriteLine(); } /// <summary> /// Displays all custom channels an ad unit has been added to. /// </summary> /// <param name="adClientId">The ID for the ad client to be used.</param> /// <param name="adUnitId">The ID for the ad unit to be used.</param> private void DisplayAllCustomChannelsForAdUnit(string adClientId, string adUnitId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all custom channels for ad unit {0}", adUnitId); CommandLine.WriteLine("================================================================="); // Retrieve custom channel list in pages and display data as we receive it. string pageToken = null; CustomChannels customChannelResponse = null; do { var customChannelRequest = this.service.Adunits.Customchannels.List(adClientId, adUnitId); customChannelRequest.MaxResults = this.maxListPageSize; customChannelRequest.PageToken = pageToken; customChannelResponse = customChannelRequest.Execute(); if (customChannelResponse.Items.IsNotNullOrEmpty()) { foreach (var customChannel in customChannelResponse.Items) { CommandLine.WriteLine( "Custom channel with code \"{0}\" and name \"{1}\" was found.", customChannel.Code, customChannel.Name); } } else { CommandLine.WriteLine("No custom channels found."); } pageToken = customChannelResponse.NextPageToken; } while (pageToken != null); CommandLine.WriteLine(); } /// <summary> /// Displays all URL channels in an ad client. /// </summary> /// <param name="adClientId">The ID for the ad client to be used.</param> private void DisplayAllUrlChannels(string adClientId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all URL channels for ad client {0}", adClientId); CommandLine.WriteLine("================================================================="); // Retrieve URL channel list in pages and display data as we receive it. string pageToken = null; UrlChannels urlChannelResponse = null; do { var urlChannelRequest = this.service.Urlchannels.List(adClientId); urlChannelRequest.MaxResults = this.maxListPageSize; urlChannelRequest.PageToken = pageToken; urlChannelResponse = urlChannelRequest.Execute(); if (urlChannelResponse.Items.IsNotNullOrEmpty()) { foreach (var urlChannel in urlChannelResponse.Items) { CommandLine.WriteLine( "URL channel with pattern \"{0}\" was found.", urlChannel.UrlPattern); } } else { CommandLine.WriteLine("No URL channels found."); } pageToken = urlChannelResponse.NextPageToken; } while (pageToken != null); CommandLine.WriteLine(); } /// <summary> /// Retrieves a report, using a filter for a specified ad client. /// </summary> /// <param name="adClientId">The ID for the ad client to be used.</param> private void GenerateReport(string adClientId) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Running report for ad client {0}", adClientId); CommandLine.WriteLine("================================================================="); // Prepare report. var startDate = DateTime.Today.ToString(DateFormat); var endDate = DateTime.Today.AddDays(-7).ToString(DateFormat); var reportRequest = this.service.Reports.Generate(startDate, endDate); // Specify the desired ad client using a filter, as well as other parameters. reportRequest.Filter = new List<string> { "AD_CLIENT_ID==" + ReportUtils.EscapeFilterParameter(adClientId) }; reportRequest.Metric = new List<string> { "PAGE_VIEWS", "AD_REQUESTS", "AD_REQUESTS_COVERAGE", "AD_REQUESTS_CTR", "COST_PER_CLICK", "AD_REQUESTS_RPM", "EARNINGS" }; reportRequest.Dimension = new List<string> { "DATE" }; reportRequest.Sort = new List<string> { "+DATE" }; // Run report. var reportResponse = reportRequest.Execute(); if (reportResponse.Rows.IsNotNullOrEmpty()) { ReportUtils.DisplayHeaders(reportResponse.Headers); ReportUtils.DisplayRows(reportResponse.Rows); } else { CommandLine.WriteLine("No rows returned."); } CommandLine.WriteLine(); } /// <summary> /// Retrieves a report for a specified ad client, using pagination. /// <para>Please only use pagination if your application requires it due to memory or storage constraints. /// If you need to retrieve more than 5000 rows, please check GenerateReport, as due to current /// limitations you will not be able to use paging for large reports.</para> /// </summary> /// <param name="adClientId">The ID for the ad client to be used.</param> private void GenerateReportWithPaging(string adClientId) { int rowLimit = 5000; CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Running paginated report for ad client {0}", adClientId); CommandLine.WriteLine("================================================================="); // Prepare report. var startDate = DateTime.Today.ToString(DateFormat); var endDate = DateTime.Today.AddDays(-7).ToString(DateFormat); var reportRequest = this.service.Reports.Generate(startDate, endDate); var pageSize = this.maxListPageSize; var startIndex = 0; // Specify the desired ad client using a filter, as well as other parameters. reportRequest.Filter = new List<string> { "AD_CLIENT_ID==" + ReportUtils.EscapeFilterParameter(adClientId) }; reportRequest.Metric = new List<string> { "PAGE_VIEWS", "AD_REQUESTS", "AD_REQUESTS_COVERAGE", "AD_REQUESTS_CTR", "COST_PER_CLICK", "AD_REQUESTS_RPM", "EARNINGS" }; reportRequest.Dimension = new List<string> { "DATE" }; reportRequest.Sort = new List<string> { "+DATE" }; // Run first page of report. var reportResponse = ReportUtils.GetPage(reportRequest, startIndex, pageSize); if (reportResponse.Rows.IsNullOrEmpty()) { CommandLine.WriteLine("No rows returned."); CommandLine.WriteLine(); return; } // Display headers. ReportUtils.DisplayHeaders(reportResponse.Headers); // Display first page of results. ReportUtils.DisplayRows(reportResponse.Rows); var totalRows = Math.Min(int.Parse(reportResponse.TotalMatchedRows), rowLimit); for (startIndex = reportResponse.Rows.Count; startIndex < totalRows; startIndex += reportResponse.Rows.Count) { // Check to see if we're going to go above the limit and get as many results as we can. pageSize = Math.Min(this.maxListPageSize, totalRows - startIndex); // Run next page of report. reportResponse = ReportUtils.GetPage(reportRequest, startIndex, pageSize); // If the report size changes in between paged requests, the result may be empty. if (reportResponse.Rows.IsNullOrEmpty()) { break; } // Display results. ReportUtils.DisplayRows(reportResponse.Rows); } CommandLine.WriteLine(); } /// <summary> /// Retrieves a report, using a filter for a specified saved report. /// </summary> /// <param name="savedReportId">The ID of the saved report to generate.</param> private void GenerateSavedReport(string savedReportId) { ReportsResource.SavedResource.GenerateRequest savedReportRequest = this.service.Reports.Saved.Generate(savedReportId); AdsenseReportsGenerateResponse savedReportResponse = savedReportRequest.Execute(); // Run report. if (savedReportResponse.Rows.IsNotNullOrEmpty()) { ReportUtils.DisplayHeaders(savedReportResponse.Headers); ReportUtils.DisplayRows(savedReportResponse.Rows); } else { CommandLine.WriteLine("No rows returned."); } CommandLine.WriteLine(); } /// <summary> /// Gets and prints all the saved reports for the logged in user's default account. /// </summary> /// <returns>The last page of the retrieved saved reports.</returns> private SavedReports GetAllSavedReports() { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all saved reports"); CommandLine.WriteLine("================================================================="); // Retrieve ad client list in pages and display data as we receive it. string pageToken = null; SavedReports savedReportResponse = null; do { var savedReportRequest = this.service.Reports.Saved.List(); savedReportRequest.MaxResults = this.maxListPageSize; savedReportRequest.PageToken = pageToken; savedReportResponse = savedReportRequest.Execute(); if (savedReportResponse.Items.IsNotNullOrEmpty()) { foreach (var savedReport in savedReportResponse.Items) { CommandLine.WriteLine( "Saved report with ID \"{0}\" and name \"{1}\" was found.", savedReport.Id, savedReport.Name); } } else { CommandLine.WriteLine("No saved saved reports found."); } pageToken = savedReportResponse.NextPageToken; } while (pageToken != null); CommandLine.WriteLine(); return savedReportResponse; } /// <summary> Displays all the saved ad styles for the logged in user's default account. </summary> private void DisplayAllSavedAdStyles() { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all saved ad styles"); CommandLine.WriteLine("================================================================="); // Retrieve ad client list in pages and display data as we receive it. string pageToken = null; SavedAdStyles savedAdStyleResponse = null; do { var savedAdStyleRequest = this.service.Savedadstyles.List(); savedAdStyleRequest.MaxResults = this.maxListPageSize; savedAdStyleRequest.PageToken = pageToken; savedAdStyleResponse = savedAdStyleRequest.Execute(); if (savedAdStyleResponse.Items.IsNotNullOrEmpty()) { foreach (var savedAdStyle in savedAdStyleResponse.Items) { CommandLine.WriteLine( "Saved ad style with ID \"{0}\" and name \"{1}\" was found.", savedAdStyle.Id, savedAdStyle.Name); } } else { CommandLine.WriteLine("No saved ad styles found."); } pageToken = savedAdStyleResponse.NextPageToken; } while (pageToken != null); CommandLine.WriteLine(); } /// <summary> /// Displays all the available metrics and dimensions for the logged in user's default account. /// </summary> private void DisplayAllMetricsAndDimensions() { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all metrics"); CommandLine.WriteLine("================================================================="); Metadata metricsResponse = this.service.Metadata.Metrics.List().Execute(); if (metricsResponse.Items.IsNotNullOrEmpty()) { foreach (var metric in metricsResponse.Items) { CommandLine.WriteLine( "Metric with ID \"{0}\" is available for products: \"{1}\".", metric.Id, String.Join(", ", metric.SupportedProducts.ToArray())); } } else { CommandLine.WriteLine("No available metrics found."); } CommandLine.WriteLine(); CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all dimensions"); CommandLine.WriteLine("================================================================="); Metadata dimensionsResponse = this.service.Metadata.Dimensions.List().Execute(); if (dimensionsResponse.Items.IsNotNullOrEmpty()) { foreach (var dimension in dimensionsResponse.Items) { CommandLine.WriteLine( "Dimension with ID \"{0}\" is available for products: \"{1}\".", dimension.Id, String.Join(", ", dimension.SupportedProducts.ToArray())); } } else { CommandLine.WriteLine("No available dimensions found."); } CommandLine.WriteLine(); } /// <summary> Prints all the alerts for the logged in user's default account. </summary> private void DisplayAllAlerts() { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all alerts"); CommandLine.WriteLine("================================================================="); Alerts alertsResponse = this.service.Alerts.List().Execute(); if (alertsResponse.Items.IsNotNullOrEmpty()) { foreach (var alert in alertsResponse.Items) { CommandLine.WriteLine( "Alert with ID \"{0}\" type \"{1}\" and severity \"{2}\" was found.", alert.Id, alert.Type, alert.Severity); } } else { CommandLine.WriteLine("No alerts found."); } CommandLine.WriteLine(); } } }
zzfocuzz-deepbotcopy
AdSense.Sample/ManagementApiConsumer.cs
C#
asf20
36,173
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AdSense.Sample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google")] [assembly: AssemblyProduct("AdSense.Sample")] [assembly: AssemblyCopyright("Copyright © Google Inc 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("05d799ca-03b7-4414-98f5-d066850a0877")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
AdSense.Sample/Properties/AssemblyInfo.cs
C#
asf20
1,456
/* Copyright 2013 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Google.Apis.Adsense.v1_3; using Google.Apis.Adsense.v1_3.Data; using Google.Apis.Samples.Helper; namespace AdSense.Sample { /// <summary> /// Collection of utilities to display and modify reports /// </summary> public static class ReportUtils { /// <summary> /// Displays the headers for the report. /// </summary> /// <param name="headers">The list of headers to be displayed</param> public static void DisplayHeaders(IList<AdsenseReportsGenerateResponse.HeadersData> headers) { foreach (var header in headers) { CommandLine.Write("{0, -25}", header.Name); } CommandLine.WriteLine(); } /// <summary> /// Displays a list of rows for the report. /// </summary> /// <param name="rows">The list of rows to display.</param> public static void DisplayRows(IList<IList<string>> rows) { foreach (var row in rows) { foreach (var column in row) { CommandLine.Write("{0, -25}", column); } CommandLine.WriteLine(); } } /// <summary> /// Escape special characters for a parameter being used in a filter. /// </summary> /// <param name="parameter">The parameter to be escaped.</param> /// <returns>The escaped parameter.</returns> public static string EscapeFilterParameter(string parameter) { return parameter.Replace("\\", "\\\\").Replace(",", "\\,"); } /// <summary> /// Returns a page of results, defined by the request and page parameters. /// </summary> /// <param name="reportRequest">An instance of the Generate request for the report.</param> /// <param name="startIndex">The starting index for this page.</param> /// <param name="pageSize">The maximum page size.</param> /// <returns>A page of results</returns> public static AdsenseReportsGenerateResponse GetPage( ReportsResource.GenerateRequest reportRequest, int startIndex, int pageSize) { reportRequest.StartIndex = startIndex; reportRequest.MaxResults = pageSize; // Run next page of report. return reportRequest.Execute(); } } }
zzfocuzz-deepbotcopy
AdSense.Sample/ReportUtils.cs
C#
asf20
3,171
/* Copyright 2013 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using DotNetOpenAuth.OAuth2; using Google.Apis.Adsense.v1_3; using Google.Apis.Adsense.v1_3.Data; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Util; namespace AdSense.Sample { /// <summary> /// A sample application that runs multiple requests against the AdSense Management API. /// <list type="bullet"> /// <item> /// <description>Registers the authenticator</description> /// </item> /// <item> /// <description>Creates the service that queries the API</description> /// </item> /// <item> /// <description>Executes the requests</description> /// </item> /// </list> /// </summary> internal class AdSenseSample { private static readonly string Scope = AdSenseService.Scopes.AdsenseReadonly.GetStringValue(); private static readonly int MaxListPageSize = 50; [STAThread] internal static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("AdSense Management API Command Line Sample"); // Register the authenticator. FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials(); NativeApplicationClient provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = credentials.ClientId, ClientSecret = credentials.ClientSecret }; OAuth2Authenticator<NativeApplicationClient> auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication); // Create the service. var service = new AdSenseService(new BaseClientService.Initializer() { Authenticator = auth }); // Execute Publisher calls ManagementApiConsumer managementApiConsumer = new ManagementApiConsumer(service, MaxListPageSize); managementApiConsumer.RunCalls(); CommandLine.PressAnyKeyToExit(); } private static IAuthorizationState GetAuthentication(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.samples.dotnet.adsense"; const string KEY = "`7X}^}voR4;.1Kr_ynFt"; IAuthorizationState state = null; try { // Check if there is a cached refresh token available. state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); } catch (System.Security.Cryptography.CryptographicException ex) { CommandLine.WriteError("Getting Refresh token failed: " + ex.Message); CommandLine.WriteLine("Requesting new authorization..."); state = null; } if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, Scope); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } } }
zzfocuzz-deepbotcopy
AdSense.Sample/AdSenseSample.cs
C#
asf20
4,557
<html> <head><title>Google .NET Client API &ndash; AdSense.Sample</title></head> <body> <h2>Instructions for the Google .NET Client API &ndash; AdSense.Sample</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FAdSense.Sample">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/AdSense.Sample/AdSenseSample.cs?repo=samples">AdSenseSample.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to:</p> <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the AdSense Management API for your project </li> </ul> <h3>Set up Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>AdSense.Sample\bin\Debug</i></li> <li> When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane. </li> </ul> <h3>Documentation</h3> <p>If you want to learn more about the API visit the <a href="https://developers.google.com/adsense/management/">AdSense Management API documentation</a>.</p> </body> </html>
zzfocuzz-deepbotcopy
AdSense.Sample/README.html
HTML
asf20
1,850
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Urlshortener.v1.Cmd")] [assembly: AssemblyDescription("URL Shortener Sample")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("Urlshortener.v1.Cmd")] [assembly: AssemblyCopyright("© 2011 Google Inc")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b4e58c0f-6600-4d38-b92a-97149c9ec01a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
UrlShortener.ShortenURL/Properties/AssemblyInfo.cs
C#
asf20
1,446
<html> <title>Google .NET Client API &ndash; UrlShortener.ShortenURL</title> <body> <h2>Instructions for the Google .NET Client API &ndash; UrlShortener.ShortenURL</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FUrlShortener.ShortenURL">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/UrlShortener.ShortenURL/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the UrlShortener API for your project </li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>UrlShortener.ShortenURL\bin\Debug</i></li> <li> When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane. </li> </ul> </body> </html>
zzfocuzz-deepbotcopy
UrlShortener.ShortenURL/README.html
HTML
asf20
1,675
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using Google.Apis.Authentication; using Google.Apis.Samples.Helper; using Google.Apis.Urlshortener.v1; using Google.Apis.Urlshortener.v1.Data; namespace Google.Apis.Samples.CmdUrlShortener { /// <summary> /// This example shows you how to use a CodeGenerated library to access Google APIs. /// In this case the URLShortener service is used to execute simple resolve & get requests. /// </summary> internal class Program { /// <summary> /// Main method /// </summary> internal static void Main(string[] args) { // Initialize this sample CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("URL Shortener"); // Create the service var service = new UrlshortenerService(); // Ask the user what he wants to do CommandLine.RequestUserChoice( "What do you want to do?", new UserOption("Create a short URL", () => CreateShortURL(service)), new UserOption("Resolve a short URL", () => ResolveShortURL(service))); CommandLine.PressAnyKeyToExit(); } private static void ResolveShortURL(UrlshortenerService service) { // Request input string urlToResolve = "http://goo.gl/hcEg7"; CommandLine.RequestUserInput("URL to resolve", ref urlToResolve); CommandLine.WriteLine(); // Resolve URL Url response = service.Url.Get(urlToResolve).Execute(); // Display response CommandLine.WriteLine(" ^1Status: ^9{0}", response.Status); CommandLine.WriteLine(" ^1Long URL: ^9{0}", response.LongUrl); } private static void CreateShortURL(UrlshortenerService service) { // Request input string urlToShorten = "http://maps.google.com/"; CommandLine.RequestUserInput("URL to shorten", ref urlToShorten); CommandLine.WriteLine(); // Shorten URL Url response = service.Url.Insert(new Url { LongUrl = urlToShorten }).Execute(); // Display response CommandLine.WriteLine(" ^1Short URL: ^9{0}", response.Id); } } }
zzfocuzz-deepbotcopy
UrlShortener.ShortenURL/Program.cs
C#
asf20
2,910
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("UrlShortener.ASP.NET")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("UrlShortener.ASP.NET")] [assembly: AssemblyCopyright("Copyright © Microsoft 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f402a950-432b-4bf0-b021-964e8da8e686")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
UrlShortener.ASP.NET/Properties/AssemblyInfo.cs
C#
asf20
1,429
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Text.RegularExpressions; using Google; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Urlshortener.v1; using Google.Apis.Urlshortener.v1.Data; namespace UrlShortener.ASP.NET { /// <summary> /// ASP.NET UrlShortener Sample /// /// This sample makes use of ASP.NET and the UrlShortener API to demonstrate how to do make unauthenticated /// requests to an api. /// </summary> public partial class _Default : System.Web.UI.Page { private static UrlshortenerService _service; protected void Page_Load(object sender, EventArgs e) { // If we did not construct the service so far, do it now. if (_service == null) { BaseClientService.Initializer initializer = new BaseClientService.Initializer(); // You can enter your developer key for services requiring a developer key. /* initializer.ApiKey = "<Insert Developer Key here>"; */ _service = new UrlshortenerService(initializer); } } protected void input_TextChanged(object sender, EventArgs e) { // Change the text of the button according to the content. action.Text = IsShortUrl(input.Text) ? "Expand" : "Shorten"; } protected void action_Click(object sender, EventArgs e) { string url = input.Text; if (string.IsNullOrEmpty(url)) { return; } // Execute methods on the UrlShortener service based upon the type of the URL provided. try { string resultURL; if (IsShortUrl(url)) { // Expand the URL by using a Url.Get(..) request. Url result = _service.Url.Get(url).Execute(); resultURL = result.LongUrl; } else { // Shorten the URL by inserting a new Url. Url toInsert = new Url { LongUrl = url }; toInsert = _service.Url.Insert(toInsert).Execute(); resultURL = toInsert.Id; } output.Text = string.Format("<a href=\"{0}\">{0}</a>", resultURL); } catch (GoogleApiException ex) { output.Text = ex.ToHtmlString(); } } private static readonly Regex ShortUrlRegex = new Regex("^http[s]?://goo.gl/", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static bool IsShortUrl(string url) { return ShortUrlRegex.IsMatch(url); } } }
zzfocuzz-deepbotcopy
UrlShortener.ASP.NET/Default.aspx.cs
C#
asf20
3,446
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UrlShortener.ASP.NET._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <h1>Urlshortener ASP.NET sample</h1> <form id="mainForm" runat="server"> <p> Please enter a shortened or a long url into the textbox, and press the button next to it. </p> <div> <asp:Label ID="Label1" runat="server" Font-Bold="True" Text="Input:"></asp:Label> &nbsp; &nbsp; <asp:TextBox ID="input" runat="server" AutoPostBack="True" ontextchanged="input_TextChanged"></asp:TextBox> <asp:Button ID="action" runat="server" Text="Shorten!" onclick="action_Click" /> </div> <p> <asp:Label ID="Label2" runat="server" Font-Bold="True" Text="Output:"></asp:Label> &nbsp; &nbsp; <asp:Label ID="output" runat="server"></asp:Label> </p> </form> <p> &copy; 2011 Google Inc</p> </body> </html>
zzfocuzz-deepbotcopy
UrlShortener.ASP.NET/Default.aspx
ASP.NET
asf20
1,173
<html> <title>Google .NET Client API &ndash; UrlShortener.ASP.NET</title> <body> <h2>Instructions for the Google .NET Client API &ndash; UrlShortener.ASP.NET</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FUrlShortener.ASP.NET">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/UrlShortener.ASP.NET/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the UrlShortener API for your project </li> <li>Edit <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/UrlShortener.ASP.NET/ClientCredentials.cs?repo=samples">ClientCredentials.cs</a> to insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane.</li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Select the project as the active project, and press F5 to run the webpage.</li> </ul> </body> </html>
zzfocuzz-deepbotcopy
UrlShortener.ASP.NET/README.html
HTML
asf20
1,816
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Linq; using System.Windows; using System.Windows.Controls; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Tasks.v1; using Google.Apis.Tasks.v1.Data; using Google.Apis.Util; namespace Tasks.WPF.ListTasks { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { /// <summary> /// The remote service on which all the requests are executed. /// </summary> public static TasksService Service { get; private set; } private static IAuthenticator CreateAuthenticator() { var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = ClientCredentials.ClientID, ClientSecret = ClientCredentials.ClientSecret }; return new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); } private static IAuthorizationState GetAuthorization(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.samples.dotnet.tasks"; const string KEY = "y},drdzf11x9;87"; string scope = TasksService.Scopes.Tasks.GetStringValue(); // Check if there is a cached refresh token available. IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, scope); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } public MainWindow() { InitializeComponent(); } private async void UpdateTaskLists() { // Notice - this is not best practice to create async void method, but for this sample it works. // Download a new version of the TaskLists and add the UI controls lists.Children.Clear(); var tasklists = await Service.Tasklists.List().ExecuteAsync(); foreach (TaskList list in tasklists.Items) { var tasks = await Service.Tasks.List(list.Id).ExecuteAsync(); Expander listUI = CreateUITasklist(list, tasks); lists.Children.Add(listUI); } } private Expander CreateUITasklist(TaskList list, Google.Apis.Tasks.v1.Data.Tasks tasks) { var expander = new Expander(); // Add a bold title. expander.Header = list.Title; expander.FontWeight = FontWeights.Bold; // Add the taskItems (if applicable). if (tasks.Items != null) { var container = new StackPanel(); foreach (CheckBox box in tasks.Items.Select(CreateUITask)) { container.Children.Add(box); } expander.Content = container; } else { expander.Content = "There are no tasks in this list."; } return expander; } private CheckBox CreateUITask(Task task) { var checkbox = new CheckBox(); checkbox.Margin = new Thickness(20, 0, 0, 0); checkbox.FontWeight = FontWeights.Normal; checkbox.Content = task.Title; checkbox.IsChecked = (task.Status == "completed"); return checkbox; } private void Window_Initialized(object sender, EventArgs e) { // Create the service. Service = new TasksService(new BaseClientService.Initializer() { Authenticator = CreateAuthenticator(), ApplicationName = "Tasks API Sample", }); // Get all TaskLists. UpdateTaskLists(); } } }
zzfocuzz-deepbotcopy
Tasks.WPF.ListTasks/MainWindow.xaml.cs
C#
asf20
5,488
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Windows; namespace Tasks.WPF.ListTasks { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
zzfocuzz-deepbotcopy
Tasks.WPF.ListTasks/App.xaml.cs
C#
asf20
321
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Tasks.WPF.ListTasks")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Tasks.WPF.ListTasks")] [assembly: AssemblyCopyright("Copyright © Microsoft 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
Tasks.WPF.ListTasks/Properties/AssemblyInfo.cs
C#
asf20
2,320
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using Google.Apis.Samples.Helper; namespace Tasks.WPF.ListTasks { /// <summary> /// This class provides the client credentials for all the samples in this solution. /// In order to run all of the samples, you have to enable API access for every API /// you want to use, enter your credentials here. /// /// You can find your credentials here: /// https://code.google.com/apis/console/#:access /// /// For your own application you should find a more secure way than just storing your client secret inside a string, /// as it can be lookup up easily using a reflection tool. /// </summary> internal static class ClientCredentials { /// <summary> /// The OAuth2.0 Client ID of your project. /// </summary> public static readonly string ClientID = "<Enter your ClientID here>"; /// <summary> /// The OAuth2.0 Client secret of your project. /// </summary> public static readonly string ClientSecret = "<Enter your ClientSecret here>"; /// <summary> /// Your Api/Developer key. /// </summary> public static readonly string ApiKey = "<Enter your ApiKey here>"; #region Verify Credentials static ClientCredentials() { ReflectionUtils.VerifyCredentials(typeof(ClientCredentials)); } #endregion } }
zzfocuzz-deepbotcopy
Tasks.WPF.ListTasks/ClientCredentials.cs
C#
asf20
2,014
<html> <title>Google .NET Client API &ndash; Tasks.WPF.ListTasks</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Tasks.WPF.ListTasks</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FTasks.WPF.ListTasks">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.WPF.ListTasks/MainWindow.xaml.cs?repo=samples">MainWindow.xaml.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Tasks API for your project </li> <li>Edit <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.WPF.ListTasks/ClientCredentials.cs?repo=samples">ClientCredentials.cs</a> to insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane.</li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Tasks.WPF.ListTasks\bin\Debug</i></li> </ul> </body> </html>
zzfocuzz-deepbotcopy
Tasks.WPF.ListTasks/README.html
HTML
asf20
1,802
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Translate.TranslateText")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("Translate.TranslateText")] [assembly: AssemblyCopyright("Copyright © Google Inc 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d7fabf5e-65ea-4bb1-921b-f4e3ad621144")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.*")] [assembly: AssemblyFileVersion("1.0.0.10")]
zzfocuzz-deepbotcopy
Translate.TranslateText/Properties/AssemblyInfo.cs
C#
asf20
1,479
<html> <title>Google .NET Client API &ndash; Translate.TranslateText</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Translate.TranslateText</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FTranslate.TranslateText">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Translate.TranslateText/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Translate API for your project </li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Translate.TranslateText\bin\Debug</i></li> <li> When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane. </li> </ul> </body> </html>
zzfocuzz-deepbotcopy
Translate.TranslateText/README.html
HTML
asf20
1,672
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.ComponentModel; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Translate.v2; using Google.Apis.Translate.v2.Data; using TranslationsResource = Google.Apis.Translate.v2.Data.TranslationsResource; namespace Translate.TranslateText { /// <summary> /// This example uses the Translate API to translate a user /// entered phrase from English to French or a language of the user's choice. /// /// Uses your DeveloperKey for authentication. /// </summary> internal class Program { /// <summary> /// User input for this example. /// </summary> [Description("input")] public class TranslateInput { [Description("text to translate")] public string SourceText = "Who ate my candy?"; [Description("target language")] public string TargetLanguage = "fr"; } [STAThread] static void Main(string[] args) { // Initialize this sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Translate Sample"); // Ask for the user input. TranslateInput input = CommandLine.CreateClassFromUserinput<TranslateInput>(); // Create the service. var service = new TranslateService(new BaseClientService.Initializer() { ApiKey = GetApiKey(), ApplicationName = "Translate API Sample" }); // Execute the first translation request. CommandLine.WriteAction("Translating to '" + input.TargetLanguage + "' ..."); string[] srcText = new[] { "Hello world!", input.SourceText }; TranslationsListResponse response = service.Translations.List(srcText, input.TargetLanguage).Execute(); var translations = new List<string>(); foreach (TranslationsResource translation in response.Translations) { translations.Add(translation.TranslatedText); CommandLine.WriteResult("translation", translation.TranslatedText); } // Translate the text (back) to english. CommandLine.WriteAction("Translating to english ..."); response = service.Translations.List(translations, "en").Execute(); foreach (TranslationsResource translation in response.Translations) { CommandLine.WriteResult("translation", translation.TranslatedText); } // ...and we are done. CommandLine.PressAnyKeyToExit(); } private static string GetApiKey() { return PromptingClientCredentials.EnsureSimpleClientCredentials().ApiKey; } } }
zzfocuzz-deepbotcopy
Translate.TranslateText/Program.cs
C#
asf20
3,545
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Tasks.ETagCollision")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("Tasks.ETagCollision")] [assembly: AssemblyCopyright("Copyright © Google Inc 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4d633636-c985-48c3-b749-bc5d06760ceb")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
Tasks.ETagCollision/Properties/AssemblyInfo.cs
C#
asf20
1,470
<html> <title>Google .NET Client API &ndash; Tasks.ETagCollision</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Tasks.ETagCollision</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FTasks.ETagCollision">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.ETagCollision/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the Tasks API for your project </li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>Tasks.ETagCollision\bin\Debug</i></li> <li> When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane. </li> </ul> </body> </html>
zzfocuzz-deepbotcopy
Tasks.ETagCollision/README.html
HTML
asf20
1,648
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using DotNetOpenAuth.OAuth2; using Google; using Google.Apis; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Tasks.v1; using Google.Apis.Tasks.v1.Data; using Google.Apis.Util; namespace Tasks.ETagCollision { /// <summary> /// This sample shows the E-Tag collision behaviour when an user tries updating an object, /// which has been modified by another source. /// </summary> internal class Program { private static readonly string Scope = TasksService.Scopes.Tasks.GetStringValue(); public static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Tasks API: E-Tag collision"); // Register the authenticator. FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials(); var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = credentials.ClientId, ClientSecret = credentials.ClientSecret }; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication); // Create the service. var service = new TasksService(new BaseClientService.Initializer() { Authenticator = auth, ApplicationName = "Tasks API Sample", }); // Run the sample code. RunSample(service, true, ETagAction.Ignore); RunSample(service, true, ETagAction.IfMatch); RunSample(service, true, ETagAction.IfNoneMatch); RunSample(service, false, ETagAction.Ignore); RunSample(service, false, ETagAction.IfMatch); RunSample(service, false, ETagAction.IfNoneMatch); CommandLine.PressAnyKeyToExit(); } private static IAuthorizationState GetAuthentication(NativeApplicationClient client) { // You should use a more secure way of storing the key here as // .NET applications can be disassembled using a reflection tool. const string STORAGE = "google.samples.dotnet.siteverification"; const string KEY = "y},drdzf11x9;87"; // Check if there is a cached refresh token available. IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY); if (state != null) { try { client.RefreshToken(state); return state; // Yes - we are done. } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { CommandLine.WriteError("Using existing refresh token failed: " + ex.Message); } } // Retrieve the authorization from the user. state = AuthorizationMgr.RequestNativeAuthorization(client, Scope); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } private static void RunSample(TasksService service, bool modify, ETagAction behaviour) { CommandLine.WriteAction("Testing for E-Tag case " + behaviour + " with modified=" + modify + "..."); // Create a new task list. TaskList list = service.Tasklists.Insert(new TaskList() { Title = "E-Tag Collision Test" }).Execute(); // Add a task Task myTask = service.Tasks.Insert(new Task() { Title = "My Task" }, list.Id).Execute(); // Retrieve a second instance of this task, modify it and commit it if (modify) { Task myTaskB = service.Tasks.Get(list.Id, myTask.Id).Execute(); myTaskB.Title = "My Task B!"; service.Tasks.Update(myTaskB, list.Id, myTaskB.Id).Execute(); } // Modfiy the original task, and see what happens myTask.Title = "My Task A!"; var request = service.Tasks.Update(myTask, list.Id, myTask.Id); request.ETagAction = behaviour; try { request.Execute(); CommandLine.WriteResult("Result", "Success!"); } catch (GoogleApiException ex) { CommandLine.WriteResult( "Result", "Failure! (" + ex.Message + ")"); } finally { // Delete the created list. service.Tasklists.Delete(list.Id).Execute(); CommandLine.WriteLine(); } } } }
zzfocuzz-deepbotcopy
Tasks.ETagCollision/Program.cs
C#
asf20
5,620
@echo off EnterCredentials\static\EnterCredentials.exe %1 %2 %3 %4 %5 %6 %7 %8
zzfocuzz-deepbotcopy
enterCredentials.cmd
Batchfile
asf20
79
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SiteVerification..VerifySite")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google")] [assembly: AssemblyProduct("SiteVerification.VerifySite")] [assembly: AssemblyCopyright("Copyright © Google Inc 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("05d799ca-03b7-4414-98f5-d066850a0877")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
SiteVerification.VerifySite/Properties/AssemblyInfo.cs
C#
asf20
1,483
<html> <title>Google .NET Client API &ndash; SiteVerification.VerifySite</title> <body> <h2>Instructions for the Google .NET Client API &ndash; SiteVerification.VerifySite</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FSiteVerification.VerifySite">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/SiteVerification.VerifySite/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the SiteVerification API for your project </li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>SiteVerification.VerifySite\bin\Debug</i></li> <li> When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane. </li> </ul> </body> </html>
zzfocuzz-deepbotcopy
SiteVerification.VerifySite/README.html
HTML
asf20
1,699
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.SiteVerification.v1; using Google.Apis.SiteVerification.v1.Data; using Google.Apis.Util; namespace SiteVerification.VerifySite { /// <summary> /// This sample goes through the site verification process by first obtaining a token, having the user /// add it to the target site, and then inserting the site into the verified owners list. It uses the /// SiteVerification API to do so. /// /// http://code.google.com/apis/siteverification/v1/getting_started.html /// </summary> internal class Program { private static readonly string Scope = SiteVerificationService.Scopes.Siteverification.GetStringValue(); [STAThread] static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Site Verification sample"); // Register the authenticator. var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description); FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials(); provider.ClientIdentifier = credentials.ClientId; provider.ClientSecret = credentials.ClientSecret; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication); // Create the service. var service = new SiteVerificationService(new BaseClientService.Initializer { Authenticator = auth, ApplicationName = "SiteVerification API Sample", }); RunVerification(service); CommandLine.PressAnyKeyToExit(); } private static IAuthorizationState GetAuthentication(NativeApplicationClient client) { // Retrieve the authorization from the user. return AuthorizationMgr.RequestNativeAuthorization(client, Scope); } /// <summary> /// This method contains the actual sample code. /// </summary> private static void RunVerification(SiteVerificationService service) { // Request user input. string site = Util.GetSingleLineClipboardContent(96); CommandLine.WriteAction("Please enter the URL of the site to verify:"); CommandLine.RequestUserInput("URL", ref site); CommandLine.WriteLine(); // Example of a GetToken call. CommandLine.WriteAction("Retrieving a meta token ..."); var request = service.WebResource.GetToken(new SiteVerificationWebResourceGettokenRequest() { VerificationMethod = "meta", Site = new SiteVerificationWebResourceGettokenRequest.SiteData() { Identifier = site, Type = "site" } }); var response = request.Execute(); CommandLine.WriteResult("Token", response.Token); Util.SetClipboard(response.Token); CommandLine.WriteLine(); CommandLine.WriteAction("Please place this token on your webpage now."); CommandLine.PressEnterToContinue(); CommandLine.WriteLine(); // Example of an Insert call. CommandLine.WriteAction("Verifiying..."); var body = new SiteVerificationWebResourceResource(); body.Site = new SiteVerificationWebResourceResource.SiteData(); body.Site.Identifier = site; body.Site.Type = "site"; var verificationResponse = service.WebResource.Insert(body, "meta").Execute(); CommandLine.WriteResult("Verification", verificationResponse.Id); CommandLine.WriteAction("Verification successful!"); } } }
zzfocuzz-deepbotcopy
SiteVerification.VerifySite/Program.cs
C#
asf20
4,781
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("PageSpeedOnline.SimpleTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("PageSpeedOnline.SimpleTest")] [assembly: AssemblyCopyright("Copyright © Google Inc 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1ff12eff-e6ed-4264-ae2d-40edb01d9093")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzfocuzz-deepbotcopy
PageSpeedOnline.SimpleTest/Properties/AssemblyInfo.cs
C#
asf20
1,444
<html> <title>Google .NET Client API &ndash; PageSpeedOnline.SimpleTest</title> <body> <h2>Instructions for the Google .NET Client API &ndash; PageSpeedOnline.SimpleTest</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FPageSpeedOnline.SimpleTest">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/PageSpeedOnline.SimpleTest/Program.cs?repo=samples">Program.cs</a></li> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio, and <a href="http://mercurial.selenic.com/">Mercurial</a>.</p> <pre><code>cd <i>[someDirectory]</i> hg clone https://code.google.com/p/google-api-dotnet-client.samples/ google-api-dotnet-client-samples</code></pre> <h3>2. API access Instructions</h3> <p><b>Important:</b> after checking out the project, and before compiling and running it, you need to: <ul> <li><a href="http://code.google.com/apis/console-help/#creatingdeletingprojects">Create a project in Google APIs console</a></li> <li><a href="http://code.google.com/apis/console-help/#activatingapis">Activate</a> the PageSpeedOnline API for your project </li> </ul> </p> <h3>Setup Project in Visual Studio</h3> <ul> <li>Open the GoogleApisSamples.sln with Visual Studio</li> <li>Click on Build &gt; Rebuild Solution</li> <li>Execute the .exe in <i>PageSpeedOnline.SimpleTest\bin\Debug</i></li> <li> When prompted insert your client credentials which are generated on the <a href="https://code.google.com/apis/console/">Google APIs Console</a> API Access pane. </li> </ul> </body> </html>
zzfocuzz-deepbotcopy
PageSpeedOnline.SimpleTest/README.html
HTML
asf20
1,694
/* Copyright 2011 Google Inc Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using Google.Apis.Pagespeedonline.v1; using Google.Apis.Samples.Helper; using Google.Apis.Services; namespace PageSpeedOnline.SimpleTest { /// <summary> /// This sample uses the Page Speed API to run a speed test on the page you specify. /// https://code.google.com/apis/pagespeedonline/v1/getting_started.html /// </summary> internal class Program { [STAThread] static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Page Speed Online API"); // Create the service. var service = new PagespeedonlineService(new BaseClientService.Initializer() { ApiKey = GetApiKey(), ApplicationName = "PageSpeedOnline API Sample", }); RunSample(service); CommandLine.PressAnyKeyToExit(); } private static void RunSample(PagespeedonlineService service) { string url = "http://example.com"; CommandLine.RequestUserInput("URL to test", ref url); CommandLine.WriteLine(); // Run the request. CommandLine.WriteAction("Measuring page score ..."); var result = service.Pagespeedapi.Runpagespeed(url).Execute(); // Display the results. CommandLine.WriteResult("Page score", result.Score); } private static string GetApiKey() { return PromptingClientCredentials.EnsureSimpleClientCredentials().ApiKey; } } }
zzfocuzz-deepbotcopy
PageSpeedOnline.SimpleTest/Program.cs
C#
asf20
2,311