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 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.Threading.Tasks; using DotNetOpenAuth.OAuth2; using Google; using Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Download; using Google.Apis.Drive.v2; using Google.Apis.Drive.v2.Data; using Google.Apis.Logging; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Upload; using Google.Apis.Util; namespace Drive.Sample { /// <summary> /// A sample for the Drive API. This samples demonstrates resumable media upload and media download. /// See https://developers.google.com/drive/ for more details regarding the Drive API. /// </summary> class Program { static Program() { // initialize the log instance ApplicationContext.RegisterLogger(new Log4NetLogger()); Logger = ApplicationContext.Logger.ForType<ResumableUpload<Program>>(); } #region Consts private const int KB = 0x400; private const int DownloadChunkSize = 256 * KB; // CHANGE THIS with full path to the file you want to upload private const string UploadFileName = @"FILE_TO_UPLOAD_HERE"; // CHANGE THIS with a download directory private const string DownloadDirectoryName = @"DIRECTORY_TO_SAVE_THE_DOWNLOADED_MEDIA_HERE"; // CHANGE THIS if you upload a file type other than a jpg private const string ContentType = @"image/jpeg"; #endregion /// <summary>The logger instance.</summary> private static readonly ILogger Logger; /// <summary>The Drive API scopes.</summary> private static readonly string[] Scopes = new[] { DriveService.Scopes.DriveFile.GetStringValue(), DriveService.Scopes.Drive.GetStringValue() }; /// <summary> /// The file which was uploaded. We will use its download Url to download it using our media downloader object. /// </summary> private static File uploadedFile; static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Drive 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 DriveService(new BaseClientService.Initializer() { Authenticator = auth, ApplicationName = "Drive API Sample", }); UploadFileAsync(service).ContinueWith(t => { // uploaded succeeded Console.WriteLine("\"{0}\" was uploaded successfully", uploadedFile.Title); DownloadFile(service, uploadedFile.DownloadUrl); DeleteFile(service, uploadedFile); }, TaskContinuationOptions.OnlyOnRanToCompletion); CommandLine.PressAnyKeyToExit(); } /// <summary>Uploads file asynchronously.</summary> private static Task<IUploadProgress> UploadFileAsync(DriveService service) { var title = UploadFileName; if (title.LastIndexOf('\\') != -1) { title = title.Substring(title.LastIndexOf('\\') + 1); } var uploadStream = new System.IO.FileStream(UploadFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); var insert = service.Files.Insert(new File { Title = title, }, uploadStream, ContentType); insert.ChunkSize = FilesResource.InsertMediaUpload.MinimumChunkSize * 2; insert.ProgressChanged += Upload_ProgressChanged; insert.ResponseReceived += Upload_ResponseReceived; var task = insert.UploadAsync(); task.ContinueWith(t => { // NotOnRanToCompletion - this code will be called if the upload fails Console.WriteLine("Upload Filed. " + t.Exception); }, TaskContinuationOptions.NotOnRanToCompletion); task.ContinueWith(t => { Logger.Debug("Closing the stream"); uploadStream.Dispose(); Logger.Debug("The stream was closed"); }); return task; } /// <summary>Downloads the media from the given URL.</summary> private static void DownloadFile(DriveService service, string url) { var downloader = new MediaDownloader(service); downloader.ChunkSize = DownloadChunkSize; // add a delegate for the progress changed event for writing to console on changes downloader.ProgressChanged += Download_ProgressChanged; // figure out the right file type base on UploadFileName extension var lastDot = UploadFileName.LastIndexOf('.'); var fileName = DownloadDirectoryName + @"\Download" + (lastDot != -1 ? "." + UploadFileName.Substring(lastDot + 1) : ""); using (var fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { var progress = downloader.Download(url, fileStream); if (progress.Status == DownloadStatus.Completed) { Console.WriteLine(fileName + " was downloaded successfully"); } else { Console.WriteLine("Download {0} was interpreted in the middle. Only {1} were downloaded. ", fileName, progress.BytesDownloaded); } } } /// <summary>Deletes the given file from drive (not the file system).</summary> private static void DeleteFile(DriveService service, File file) { CommandLine.WriteLine("Deleting file '{0}'...", file.Id); service.Files.Delete(file.Id).Execute(); CommandLine.WriteLine("File was deleted successfully"); } #region Progress and Response changes static void Download_ProgressChanged(IDownloadProgress progress) { Console.WriteLine(progress.Status + " " + progress.BytesDownloaded); } static void Upload_ProgressChanged(IUploadProgress progress) { Console.WriteLine(progress.Status + " " + progress.BytesSent); } static void Upload_ResponseReceived(File file) { uploadedFile = file; } #endregion 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.drive"; 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, Scopes); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } } }
zzfocuzz-
Drive.Sample/Program.cs
C#
asf20
9,129
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("Drive.Sample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google")] [assembly: AssemblyProduct("Drive.Sample")] [assembly: AssemblyCopyright("Copyright © Google 2013")] [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("14001d69-d1ae-474b-9cd7-2a95731b8417")] // 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-
Drive.Sample/Properties/AssemblyInfo.cs
C#
asf20
1,448
<html> <title>Google .NET Client API &ndash; Drive.Sample</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Drive.Sample</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FDrive.Sample">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Drive.Sample/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 Drive API</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>Drive.Sample\bin\Debug</i></li> </ul> </body> </html>
zzfocuzz-
Drive.Sample/README.html
HTML
asf20
1,433
/* 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-
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("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-
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-
Prediction.HostedExample/README.html
HTML
asf20
1,697
/* 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-
Plus.ServiceAccount/Program.cs
C#
asf20
3,999
<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-
Plus.ServiceAccount/README.html
HTML
asf20
1,777
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-
Tasks.WPF.ListTasks/App.xaml.cs
C#
asf20
321
/* 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-
Tasks.WPF.ListTasks/ClientCredentials.cs
C#
asf20
2,014
/* 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-
Tasks.WPF.ListTasks/MainWindow.xaml.cs
C#
asf20
5,488
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-
Tasks.WPF.ListTasks/Properties/AssemblyInfo.cs
C#
asf20
2,320
<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-
Tasks.WPF.ListTasks/README.html
HTML
asf20
1,802
/* 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.Threading; using DotNetOpenAuth.OAuth2; using Google.Apis.Authentication; 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.Simple { /// <summary> /// Sample for the prediction API. /// This sample trains a simple model, and makes a prediction on the user input. /// /// This sample requires you to have the file specified in ClientCredentials.cs uploaded to Google-Storage. /// Instructions on enabling G-Storage: http://code.google.com/apis/storage/docs/signup.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. var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description) { ClientIdentifier = ClientCredentials.ClientID, ClientSecret = ClientCredentials.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) { // Train the service with the existing bucket data. string id = ClientCredentials.BucketPath; CommandLine.WriteAction("Performing training of the service ..."); CommandLine.WriteResult("Bucket", id); Training training = new Training { Id = id }; training = service.Training.Insert(training).Execute(); // Wait until the training is complete. while (training.TrainingStatus == "RUNNING") { CommandLine.Write(".."); Thread.Sleep(1000); training = service.Training.Get(id).Execute(); } CommandLine.WriteLine(); CommandLine.WriteAction("Training complete!"); CommandLine.WriteLine(); // 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.Training.Predict(input, id).Execute(); CommandLine.WriteResult("Language", result.OutputLabel); } } }
zzfocuzz-
Prediction.Simple/Program.cs
C#
asf20
5,243
/* 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 Prediction.Simple { /// <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 Google-storage bucket, and the file which is used for prediction. /// </summary> public static readonly string BucketPath = "<My Bucket>/language_id.txt"; #region Verify Credentials static ClientCredentials() { ReflectionUtils.VerifyCredentials(typeof(ClientCredentials)); } #endregion } }
zzfocuzz-
Prediction.Simple/ClientCredentials.cs
C#
asf20
2,066
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.Simple")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("Prediction.Simple")] [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("a3949ef2-c68f-4ef2-a809-222418766e4e")] // 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-
Prediction.Simple/Properties/AssemblyInfo.cs
C#
asf20
1,466
<html> <title>Google .NET Client API &ndash; Prediction.Simple</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Prediction.Simple</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FPrediction.Simple">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Prediction.Simple/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> <li>Edit <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Prediction.Simple/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>3. Uploading a file containing prediction data</h3> In order to predict something, you first have to upload a file containing prediction data and train the system. This project contains a simple sample set of data, <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Prediction.Simple/language_id.txt?repo=samples">language_id.txt</a>, which you can upload to <a href="https://code.google.com/apis/console/b/0/#project:storage:access">Google Storage</a>. <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.Simple\bin\Debug</i></li> </ul> </body> </html>
zzfocuzz-
Prediction.Simple/README.html
HTML
asf20
2,279
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("Discovery.VB.ListAPIs")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("Microsoft")> <Assembly: AssemblyProduct("Discovery.VB.ListAPIs")> <Assembly: AssemblyCopyright("Copyright © Microsoft 2011")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("1dce71e9-b3b6-452e-9fb3-011567ea293f")> ' 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-
Discovery.VB.ListAPIs/My Project/AssemblyInfo.vb
Visual Basic .NET
asf20
1,213
'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. ' Imports Google.Apis.Discovery.v1 Imports Google.Apis.Discovery.v1.Data Imports Google.Apis.Samples.Helper ''' <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 Shared Sub Main() ' Display the header and initialize the sample. CommandLine.EnableExceptionHandling() CommandLine.DisplayGoogleSampleHeader("Discovery API") ' Create the service. Dim service = New DiscoveryService() RunSample(service) CommandLine.PressAnyKeyToExit() End Sub Private Shared Sub RunSample(ByVal service As DiscoveryService) ' Run the request. CommandLine.WriteAction("Executing List-request ...") Dim result = service.Apis.List().Execute() ' Display the results. If result.Items IsNot Nothing Then For Each api As DirectoryList.ItemsData In result.Items CommandLine.WriteResult(api.Id, api.Title) Next End If End Sub End Class
zzfocuzz-
Discovery.VB.ListAPIs/Program.vb
Visual Basic .NET
asf20
1,714
<html> <title>Google .NET Client API &ndash; Discovery.VB.ListAPIs</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Discovery.VB.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.VB.ListAPIs">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Discovery.VB.ListAPIs/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>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.VB.ListAPIs\bin\Debug</i></li> </ul> </body> </html>
zzfocuzz-
Discovery.VB.ListAPIs/README.html
HTML
asf20
1,064
/* 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-
Discovery.FieldsParameter/Program.cs
C#
asf20
2,016
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-
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-
Discovery.FieldsParameter/README.html
HTML
asf20
1,084
/* 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; namespace DfaReporting.Sample { /// <summary> /// This simple utility converts <c>DateTime</c> objects to the <c>string</c> format that the DFA Reporting API /// always expects dates to be in. /// </summary> internal static class DfaReportingDateConverterUtil { private const string DateFormat = "yyyy-MM-dd"; /// <summary> /// Takes a <c>DateTime</c> object and converts it to the proper <c>string</c> format for the /// Dfa Reporting API. /// </summary> /// <param name="date">The date to be converted.</param> /// <returns>The given date in the proper format.</returns> public static string convert(DateTime date) { return date.ToString(DateFormat); } } }
zzfocuzz-
DfaReporting.Sample/DfaReportingDateConverterUtil.cs
C#
asf20
1,357
/* 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 Google.Apis.Dfareporting.v1_2; using Google.Apis.Dfareporting.v1_2.Data; using Google.Apis.Samples.Helper; namespace DfaReporting.Sample { /// <summary> /// This example gets all reports available to the given user profile. /// </summary> internal class GetAllReportsHelper { private readonly DfareportingService service; /// <summary> /// Instantiate a helper for listing all reports available. /// </summary> /// <param name="service">DfaReporting service object used to run the requests.</param> public GetAllReportsHelper(DfareportingService service) { this.service = service; } /// <summary> /// Lists all available reports for the given user profile. /// </summary> /// <param name="userProfileId">The ID number of the DFA user profile to run this request as.</param> /// <param name="maxPageSize">The maximum number of results per page.</param> public void List(string userProfileId, int maxPageSize) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all reports"); CommandLine.WriteLine("================================================================="); // Retrieve account list in pages and display data as we receive it. string pageToken = null; ReportList reports = null; do { var request = service.Reports.List(userProfileId); request.MaxResults = maxPageSize; request.PageToken = pageToken; reports = request.Execute(); foreach (var report in reports.Items) { CommandLine.WriteLine("Report with ID \"{0}\" and display name \"{1}\" was found.%n", report.Id, report.Name); } pageToken = reports.NextPageToken; } while (reports.Items.Count > 0); CommandLine.WriteLine(); } } }
zzfocuzz-
DfaReporting.Sample/GetAllReportsHelper.cs
C#
asf20
2,765
/* 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 Google.Apis.Dfareporting.v1_2; using Google.Apis.Dfareporting.v1_2.Data; using Google.Apis.Samples.Helper; namespace DfaReporting.Sample { /// <summary> /// Lists all DFA user profiles associated with your Google Account. /// </summary> internal class GetAllUserProfilesHelper { private readonly DfareportingService service; /// <summary> /// Instantiate a helper for listing the DFA user profiles associated with your Google Account. /// </summary> /// <param name="service">DfaReporting service object used to run the requests.</param> public GetAllUserProfilesHelper(DfareportingService service) { this.service = service; } /// <summary> /// Runs this sample. /// </summary> /// <returns>The list of user profiles received.</returns> public UserProfileList Run() { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing all DFA user profiles"); CommandLine.WriteLine("================================================================="); // Retrieve DFA user profiles and display them. User profiles do not support // paging. var profiles = service.UserProfiles.List().Execute(); if (profiles.Items.Count > 0) { foreach (var profile in profiles.Items) { CommandLine.WriteLine("User profile with ID \"{0}\" and name \"{1}\" was found.", profile.ProfileId, profile.UserName); } } else { CommandLine.WriteLine("No profiles found."); } CommandLine.WriteLine(); return profiles; } } }
zzfocuzz-
DfaReporting.Sample/GetAllUserProfilesHelper.cs
C#
asf20
2,521
/* 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.Dfareporting.v1_2; using Google.Apis.Dfareporting.v1_2.Data; using Google.Apis.Samples.Helper; namespace DfaReporting.Sample { /// <summary> /// This example creates a simple standard report for the given advertiser. /// </summary> internal class CreateStandardReportHelper { private readonly DfareportingService service; /// <summary> /// Instantiate a helper for creating standard reports. /// </summary> /// <param name="service">DfaReporting service object used to run the requests.</param> public CreateStandardReportHelper(DfareportingService service) { this.service = service; } /// <summary> /// Inserts (creates) a simple standard report for a given advertiser. /// </summary> /// <param name="userProfileId">The ID number of the DFA user profile to run this request as.</param> /// <param name="advertiser">The advertiser who the report is about.</param> /// <param name="startDate">The starting date of the report.</param> /// <param name="endDate">The ending date of the report.</param> /// <returns>The newly created report</returns> public Report Insert(string userProfileId, DimensionValue advertiser, DateTime startDate, DateTime endDate) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Creating a new standard report for advertiser {0}%n", advertiser.Value); CommandLine.WriteLine("================================================================="); // Create a report. var report = new Report(); report.Name = string.Format("API Report: Advertiser {0}", advertiser.Value); report.FileName = "api_report_files"; // Set the type of report you want to create. Available report types can be found in the description of // the type property: https://developers.google.com/doubleclick-advertisers/reporting/v1.1/reports report.Type = "FLOODLIGHT"; report.Type = "STANDARD"; // Create criteria. var criteria = new Report.CriteriaData(); criteria.DateRange = new DateRange { StartDate = DfaReportingDateConverterUtil.convert(startDate), EndDate = DfaReportingDateConverterUtil.convert(endDate) }; // Set the dimensions, metrics, and filters you want in the report. The available values can be found // here: https://developers.google.com/doubleclick-advertisers/reporting/v1.1/dimensions criteria.Dimensions = new List<SortedDimension> { new SortedDimension { Name = "dfa:advertiser" } }; criteria.MetricNames = new List<string> { "dfa:clicks", "dfa:impressions" }; criteria.DimensionFilters = new List<DimensionValue> { advertiser }; report.Criteria = criteria; Report result = service.Reports.Insert(report, userProfileId).Execute(); CommandLine.WriteLine("Created report with ID \"{0}\" and display name \"{1}\"", result.Id, result.Name); CommandLine.WriteLine(); return result; } } }
zzfocuzz-
DfaReporting.Sample/CreateStandardReportHelper.cs
C#
asf20
4,068
/* 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 Google.Apis.Authentication.OAuth2; using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; using Google.Apis.Dfareporting.v1_2; using Google.Apis.Dfareporting.v1_2.Data; using Google.Apis.Samples.Helper; using Google.Apis.Services; using Google.Apis.Util; namespace DfaReporting.Sample { /// <summary> /// A sample application that runs multiple requests against the DFA Reporting API. These include: /// <list type="bullet"> /// <item> /// <description>Listing all DFA user profiles for a user</description> /// </item> /// <item> /// <description>Listing the first 50 available advertisers for a user profile</description> /// </item> /// <item> /// <description>Creating a new standard report</description> /// </item> /// <item> /// <description>Listing the first 50 available Floodlight configuration IDs for a user profile</description> /// </item> /// <item> /// <description>Creating a new shared Floodlight report</description> /// </item> /// <item> /// <description>Generating a new report file from a report</description> /// </item> /// <item> /// <description>Downloading the contents of a report file</description> /// </item> /// <item> /// <description>Listing all available reports</description> /// </item> /// </list> /// </summary> internal class Program { private static readonly string DfaReportingScope = DfareportingService.Scopes.Dfareporting.GetStringValue(); private const string DevStorageScopeReadOnly = "https://www.googleapis.com/auth/devstorage.read_only"; private const int MaxListPageSize = 50; private const int MaxReportPageSize = 10; private static readonly DateTime StartDate = DateTime.Today.AddDays(-7); private static readonly DateTime EndDate = DateTime.Today; [STAThread] static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("DFA Reporting API Command Line Sample"); // 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 DfareportingService(new BaseClientService.Initializer { Authenticator = auth, ApplicationName = "DFA API Sample", }); // Choose a user profile ID to use in the following samples. string userProfileId = GetUserProfileId(service); // Create and run a standard report. CreateAndRunStandardReport(service, userProfileId); // Create and run a Floodlight report. CreateAndRunFloodlightReport(service, userProfileId); // List all of the Reports you have access to. new GetAllReportsHelper(service).List(userProfileId, MaxReportPageSize); CommandLine.PressAnyKeyToExit(); } private static string GetUserProfileId(DfareportingService service) { UserProfileList userProfiles = new GetAllUserProfilesHelper(service).Run(); if (userProfiles.Items.Count == 0) { CommandLine.WriteLine("No user profiles found."); CommandLine.PressAnyKeyToExit(); Environment.Exit(1); } return userProfiles.Items[0].ProfileId; } private static void CreateAndRunStandardReport(DfareportingService service, string userProfileId) { DimensionValueList advertisers = new GetDimensionValuesHelper(service).Query( "dfa:advertiser", userProfileId, StartDate, EndDate, MaxListPageSize); if (advertisers.Items.Count > 0) { // Get an advertiser to report on. DimensionValue advertiser = advertisers.Items[0]; Report standardReport = new CreateStandardReportHelper(service).Insert( userProfileId, advertiser, StartDate, EndDate); File file = new GenerateReportFileHelper(service).Run(userProfileId, standardReport, true); if (file != null) { // If the report file generation did not fail, display results. new DownloadReportFileHelper(service).Run(file); } } } private static void CreateAndRunFloodlightReport(DfareportingService service, string userProfileId) { DimensionValueList floodlightConfigIds = new GetDimensionValuesHelper(service).Query( "dfa:floodlightConfigId", userProfileId, StartDate, EndDate, MaxListPageSize); if (floodlightConfigIds.Items.Count > 0) { // Get a Floodlight Config ID, so we can run the rest of the samples. DimensionValue floodlightConfigId = floodlightConfigIds.Items[0]; Report floodlightReport = new CreateFloodlightReportHelper(service).Insert( userProfileId, floodlightConfigId, StartDate, EndDate); File file = new GenerateReportFileHelper(service).Run(userProfileId, floodlightReport, false); if (file != null) { // If the report file generation did not fail, display results. new DownloadReportFileHelper(service).Run(file); } } } 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.dfareporting"; const string KEY = "GV^F*(#$:P_NLOn890HC"; // 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, DfaReportingScope, DevStorageScopeReadOnly); AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state); return state; } } }
zzfocuzz-
DfaReporting.Sample/Program.cs
C#
asf20
8,074
/* 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.Dfareporting.v1_2; using Google.Apis.Dfareporting.v1_2.Data; using Google.Apis.Samples.Helper; namespace DfaReporting.Sample { /// <summary> /// This example creates a simple Floodlight report for the given Floodlight Configuration ID. /// </summary> internal class CreateFloodlightReportHelper { private readonly DfareportingService service; /// <summary> /// Instantiate a helper for creating floodlight reports. /// </summary> /// <param name="service">DfaReporting service object used to run the requests.</param> public CreateFloodlightReportHelper(DfareportingService service) { this.service = service; } /// <summary> /// Inserts (creates) a simple Floodlight report for a given Floodlight Configuration ID. /// </summary> /// <param name="userProfileId">The ID number of the DFA user profile to run this request as.</param> /// <param name="floodlightConfigId">The Floodlight configuration ID the report is about.</param> /// <param name="startDate">The starting date of the report.</param> /// <param name="endDate">The ending date of the report.</param> /// <returns>The newly created report</returns> public Report Insert(string userProfileId, DimensionValue floodlightConfigId, DateTime startDate, DateTime endDate) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Creating a new floodlight report for Floodlight config ID {0}", floodlightConfigId.Value); CommandLine.WriteLine("================================================================="); // Create a report. Report report = new Report(); report.Name = string.Format("API Floodlight Report: Floodlight ID {0}", floodlightConfigId.Value); report.FileName = "api_floodlight_report_files"; // Set the type of report you want to create. Available report types can be found in the description of // the type property: https://developers.google.com/doubleclick-advertisers/reporting/v1.1/reports report.Type = "FLOODLIGHT"; // Create criteria. var criteria = new Report.FloodlightCriteriaData(); criteria.DateRange = new DateRange { StartDate = DfaReportingDateConverterUtil.convert(startDate), EndDate = DfaReportingDateConverterUtil.convert(endDate) }; // Set the dimensions, metrics, and filters you want in the report. The available values can be found // here: https://developers.google.com/doubleclick-advertisers/reporting/v1.1/dimensions criteria.Dimensions = new List<SortedDimension> { new SortedDimension { Name = "dfa:floodlightConfigId" }, new SortedDimension { Name = "dfa:activity" }, new SortedDimension { Name = "dfa:advertiser" } }; criteria.MetricNames = new List<string> { "dfa:activityClickThroughConversions", "dfa:activityClickThroughRevenue", "dfa:activityViewThroughConversions", "dfa:activityViewThroughRevenue" }; criteria.DimensionFilters = new List<DimensionValue> { floodlightConfigId }; report.FloodlightCriteria = criteria; Report result = service.Reports.Insert(report, userProfileId).Execute(); CommandLine.WriteLine("Created report with ID \"{0}\" and display name \"{1}\"", result.Id, result.Name); CommandLine.WriteLine(); return result; } } }
zzfocuzz-
DfaReporting.Sample/CreateFloodlightReportHelper.cs
C#
asf20
4,499
/* 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 Google.Apis.Dfareporting.v1_2; using Google.Apis.Dfareporting.v1_2.Data; using Google.Apis.Samples.Helper; namespace DfaReporting.Sample { /// <summary> /// This example gets the first page of a particular type of dimension available for reporting in /// the given date range. You can use a similar workflow to retrieve the values for any dimension. /// /// The available dimension value names can be found here: /// https://developers.google.com/doubleclick-advertisers/reporting/v1.1/dimensions /// </summary> internal class GetDimensionValuesHelper { private readonly DfareportingService service; /// <summary> /// Instantiate a helper for retrieving dimension values. /// </summary> /// <param name="service">DfaReporting service object used to run the requests.</param> public GetDimensionValuesHelper(DfareportingService service) { this.service = service; } /// <summary> /// Lists the first page of results for a dimension value. /// </summary> /// <param name="dimensionName">The name of the dimension to retrieve values for.</param> /// <param name="userProfileId">The ID number of the DFA user profile to run this request as.</param> /// <param name="startDate">Values which existed after this start date will be returned.</param> /// <param name="endDate">Values which existed before this end date will be returned.</param> /// <param name="maxPageSize">The maximum page size to retrieve.</param> /// <returns>The first page of dimension values received.</returns> public DimensionValueList Query(string dimensionName, string userProfileId, DateTime startDate, DateTime endDate, int maxPageSize) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Listing available {0} values", dimensionName); CommandLine.WriteLine("================================================================="); // Create a dimension value query which selects available dimension values. var request = new DimensionValueRequest(); request.DimensionName = dimensionName; request.StartDate = DfaReportingDateConverterUtil.convert(startDate); request.EndDate = DfaReportingDateConverterUtil.convert(endDate); var dimensionQuery = service.DimensionValues.Query(request, userProfileId); dimensionQuery.MaxResults = maxPageSize; // Retrieve values and display them. var values = dimensionQuery.Execute(); if (values.Items.Count > 0) { foreach (var dimensionValue in values.Items) { CommandLine.WriteLine("{0} with value \"{1}\" was found.", dimensionName, dimensionValue.Value); } } else { CommandLine.WriteLine("No values found."); } CommandLine.WriteLine(); return values; } } }
zzfocuzz-
DfaReporting.Sample/GetDimensionValuesHelper.cs
C#
asf20
3,875
/* 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.Threading; using Google.Apis.Dfareporting.v1_2; using Google.Apis.Dfareporting.v1_2.Data; using Google.Apis.Samples.Helper; using Google.Apis.Util; namespace DfaReporting.Sample { /// <summary> /// This example generates a report file from a report. /// </summary> internal class GenerateReportFileHelper { private readonly DfareportingService service; /// <summary> /// Instantiate a helper for generating a new file for a report. /// </summary> /// <param name="service">DfaReporting service object used to run the requests.</param> public GenerateReportFileHelper(DfareportingService service) { this.service = service; } /// <summary> /// Requests the generation of a new report file from a given report. /// </summary> /// <param name="userProfileId">The ID number of the DFA user profile to run this request as.</param> /// <param name="report">The report to request a new file for.</param> /// <returns>The generated report file.</returns> public File Run(string userProfileId, Report report, bool isSynchronous) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Generating a report file for report with ID {0}", report.Id); CommandLine.WriteLine("================================================================="); ReportsResource.RunRequest request = service.Reports.Run(userProfileId, report.Id); request.Synchronous = isSynchronous; File reportFile = request.Execute(); CommandLine.WriteLine("Report execution initiated. Checking for completion..."); reportFile = waitForReportRunCompletion(service, userProfileId, reportFile); if (!reportFile.Status.Equals("REPORT_AVAILABLE")) { CommandLine.WriteLine("Report file generation failed to finish. Final status is: {0}", reportFile.Status); return null; } CommandLine.WriteLine("Report file with ID \"{0}\" generated.", reportFile.Id); CommandLine.WriteLine(); return reportFile; } /// <summary> /// Waits for a report file to generate by polling for its status using exponential backoff. In the worst case, /// there will be 10 attempts to determine if the report is no longer processing. /// </summary> /// <param name="service">DfaReporting service object used to run the requests.</param> /// <param name="userProfileId">The ID number of the DFA user profile to run this request as.</param> /// <param name="file">The report file to poll the status of.</param> /// <returns>The report file object, either once it is no longer processing or /// once too much time has passed.</returns> private static File waitForReportRunCompletion(DfareportingService service, string userProfileId, File file) { ExponentialBackOff backOff = new ExponentialBackOff(); TimeSpan interval; file = service.Reports.Files.Get(userProfileId, file.ReportId, file.Id).Execute(); for (int i = 1; i <= backOff.MaxNumOfRetries; i++) { if (!file.Status.Equals("PROCESSING")) { break; } interval = backOff.GetNextBackOff(i); CommandLine.WriteLine("Polling again in {0} seconds.", interval); Thread.Sleep(interval); file = service.Reports.Files.Get(userProfileId, file.ReportId, file.Id).Execute(); } return file; } } }
zzfocuzz-
DfaReporting.Sample/GenerateReportFileHelper.cs
C#
asf20
4,551
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("DfaReporting.Sample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google")] [assembly: AssemblyProduct("DfaReporting.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-
DfaReporting.Sample/Properties/AssemblyInfo.cs
C#
asf20
1,427
<html> <title>Google .NET Client API &ndash; DfaReporting.Sample</title> <body> <h2>Instructions for the Google .NET Client API &ndash; DfaReporting.Sample</h2> <h3>Browse Online</h3> <ul> <li> <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FDfaReporting.Sample"> Browse Source </a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/DfaReporting.Sample/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></code></pre> <pre><code>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 DFA Reporting API for your project </li> </ul> </p> <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>DfaReporting.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> </body> </html>
zzfocuzz-
DfaReporting.Sample/README.html
HTML
asf20
1,971
/* 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.IO; using System.Net; using Google.Apis.Dfareporting.v1_2; using Google.Apis.Dfareporting.v1_2.Data; using File = Google.Apis.Dfareporting.v1_2.Data.File; using Google.Apis.Samples.Helper; namespace DfaReporting.Sample { /// <summary> /// This example downloads the contents of a report file. /// </summary> internal class DownloadReportFileHelper { private readonly DfareportingService service; /// <summary> /// Instantiate a helper for downloading the contents of report files. /// </summary> /// <param name="service">DfaReporting service object used to run the requests.</param> public DownloadReportFileHelper(DfareportingService service) { this.service = service; } /// <summary> /// Fetches the contents of a report file. /// </summary> /// <param name="reportFile">The completed report file to download.</param> public void Run(File reportFile) { CommandLine.WriteLine("================================================================="); CommandLine.WriteLine("Retrieving and printing a report file for report with ID {0}", reportFile.ReportId); CommandLine.WriteLine("The ID number of this report file is {0}", reportFile.Id); CommandLine.WriteLine("================================================================="); string url = reportFile.Urls.ApiUrl; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); service.Authenticator.ApplyAuthenticationToRequest(webRequest); using (Stream stream = webRequest.GetResponse().GetResponseStream()) { StreamReader reader = new StreamReader(new BufferedStream(stream)); string report = reader.ReadToEnd(); CommandLine.WriteLine(report); } } } }
zzfocuzz-
DfaReporting.Sample/DownloadReportFileHelper.cs
C#
asf20
2,530
/* 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-
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("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-
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-
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 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-
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("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-
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-
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 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-
Tasks.SimpleOAuth2/Program.cs
C#
asf20
3,376
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-
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-
Tasks.SimpleOAuth2/README.html
HTML
asf20
1,643
/* 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-
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 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-
AdSenseHost.Sample/ReportHelper.cs
C#
asf20
2,224
/* 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-
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 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-
AdSenseHost.Sample/AdSenseHostSample.cs
C#
asf20
4,782
/* 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-
AdSenseHost.Sample/PublisherApiConsumer.cs
C#
asf20
15,462
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-
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-
AdSenseHost.Sample/README.html
HTML
asf20
1,677
/* 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-
AdSense.Sample/ManagementApiConsumer.cs
C#
asf20
36,173
/* 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-
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-
AdSense.Sample/AdSenseSample.cs
C#
asf20
4,557
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-
AdSense.Sample/Properties/AssemblyInfo.cs
C#
asf20
1,456
<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-
AdSense.Sample/README.html
HTML
asf20
1,850
/* 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-
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.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-
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 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-
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; 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-
SampleHelper/UserOption.cs
C#
asf20
1,524
/* 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-
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; 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-
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-
SampleHelper/ReflectionUtils.cs
C#
asf20
4,718
/* 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-
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; 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-
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; 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-
SampleHelper/PromptingClientCredentials.cs
C#
asf20
11,503
/* 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-
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-
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-
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.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-
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.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-
SampleHelper/Util.cs
C#
asf20
2,523
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-
SampleHelper/Properties/AssemblyInfo.cs
C#
asf20
1,446
<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-
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 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-
PageSpeedOnline.SimpleTest/Program.cs
C#
asf20
2,311
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-
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-
PageSpeedOnline.SimpleTest/README.html
HTML
asf20
1,694
<html> <title>Google .NET Client API &ndash; Samples solution</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Samples solution</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse?repo=samples">Browse Source</a> </ul> <h3>1. Checkout Instructions</h3> <p><b>Prerequisites:</b> Install Visual Studio or <a href="http://monodevelop.com/">MonoDevelop</a>, 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 APIs you want to use </li> <li>Enter your client credentials by executing enterCredentials.cmd (or running "chmod +x configure && ./configure" on Unix) You can find your credentials 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>Pick a sample, and execute the .exe in <i>&lt;SampleDir&gt;\bin\Debug</i></li> </ul> <h3>Setup Project in MonoDevelop</h3> <ul> <li>Open the GoogleApisSamples_mono.sln with MonoDevelop</li> <li>Click on Build &gt; Rebuild All</li> <li>Pick a sample, and execute the .exe in <i>&lt;SampleDir&gt;\bin\Debug</i> using mono</li> </ul> </body> </html>
zzfocuzz-
README.html
HTML
asf20
1,854
/* 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.Samples.Helper; using Google.Apis.Services; using Google.Apis.Shopping.v1; using Google.Apis.Shopping.v1.Data; namespace Shopping.ListProducts { /// <summary> /// This sample uses the Shopping API to list a set of products. /// http://code.google.com/apis/shopping/search/v1/getting_started.html /// </summary> class Program { [STAThread] static void Main(string[] args) { // Display the header and initialize the sample. CommandLine.EnableExceptionHandling(); CommandLine.DisplayGoogleSampleHeader("Shopping API: List products"); // Create the service. var service = new ShoppingService(new BaseClientService.Initializer() { ApiKey = GetApiKey(), ApplicationName = "Shopping API Sample", }); RunSample(service); CommandLine.PressAnyKeyToExit(); } private static string GetApiKey() { return PromptingClientCredentials.EnsureSimpleClientCredentials().ApiKey; } static void RunSample(ShoppingService service) { // Build the request. string query = "Camera"; CommandLine.RequestUserInput("Product to search for", ref query); CommandLine.WriteLine(); CommandLine.WriteAction("Executing request ..."); var request = service.Products.List("public"); request.Country = "us"; request.Q = query; // Parse the response. long startIndex = 1; do { request.StartIndex = startIndex; Products response = request.Execute(); if (response.CurrentItemCount == 0) { break; // Nothing more to list. } // Show the items. foreach (Product item in response.Items) { CommandLine.WriteResult((startIndex++) + ". Result", item.ProductValue.Title.TrimByLength(60)); } } while (CommandLine.RequestUserChoice("Do you want to see more items?")); } } }
zzfocuzz-
Shopping.ListProducts/Program.cs
C#
asf20
2,924
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("Shopping.ListProducts")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Google Inc")] [assembly: AssemblyProduct("Shopping.ListProducts")] [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("c445e21e-46f4-4682-91c2-af2424a70e7f")] // 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-
Shopping.ListProducts/Properties/AssemblyInfo.cs
C#
asf20
1,474
<html> <title>Google .NET Client API &ndash; Shopping.ListProducts</title> <body> <h2>Instructions for the Google .NET Client API &ndash; Shopping.ListProducts</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-dotnet-client/source/browse/?repo=samples#hg%2FShopping.ListProducts">Browse Source</a>, or main file <a href="http://code.google.com/p/google-api-dotnet-client/source/browse/Shopping.ListProducts/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 Shopping 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>Shopping.ListProducts\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-
Shopping.ListProducts/README.html
HTML
asf20
1,661
/** * Copyright 2010 Ryszard Wiśniewski <brut.alll@gmail.com> * * 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 brut.directory; public class PathAlreadyExists extends DirectoryException { public PathAlreadyExists() { } public PathAlreadyExists(Throwable throwable) { super(throwable); } public PathAlreadyExists(String detailMessage) { super(detailMessage); } public PathAlreadyExists(String detailMessage, Throwable throwable) { super(detailMessage, throwable); } private static final long serialVersionUID = 3776428251424428904L; }
zztobat-apktool
brut.j.dir/src/main/java/brut/directory/PathAlreadyExists.java
Java
asf20
1,133
/** * Copyright 2010 Ryszard Wiśniewski <brut.alll@gmail.com> * * 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 brut.directory; import brut.common.BrutException; public class DirectoryException extends BrutException { private static final long serialVersionUID = -8871963042836625387L; public DirectoryException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); } public DirectoryException(String detailMessage) { super(detailMessage); } public DirectoryException(Throwable throwable) { super(throwable); } public DirectoryException() { super(); } }
zztobat-apktool
brut.j.dir/src/main/java/brut/directory/DirectoryException.java
Java
asf20
1,186
/** * Copyright 2010 Ryszard Wiśniewski <brut.alll@gmail.com> * * 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 brut.directory; // //import java.io.InputStream; //import java.io.OutputStream; //import java.util.LinkedHashSet; //import java.util.Map; //import java.util.Set; // //public class ChangesWrapperDirectory implements Directory { // private Directory mOriginal; // private Directory mChanges; // private Set<String> mRemoved; // // public ChangesWrapperDirectory(Directory original, Directory changes) { // this(original, changes, new LinkedHashSet<String>()); // } // // public ChangesWrapperDirectory(Directory original, Directory changes, // Set<String> removed) { // super(); // mOriginal = original; // mChanges = changes; // mRemoved = removed; // } // // public Directory getOriginal() { // return mOriginal; // } // // public Directory getChanges() { // return mChanges; // } // // public Set<String> getRemoved() { // return mRemoved; // } // // @Override // public boolean containsDir(String path) { // return ! getRemoved().contains(path) && (getOriginal().containsDir(path) || getChanges().containsDir(path)); // } // // @Override // public boolean containsFile(String path) { // return ! getRemoved().contains(path) && (getOriginal().containsFile(path) || getChanges().containsFile(path)); // } // // @Override // public Directory createDir(String path) throws PathAlreadyExists, // DirectoryException { // throw new UnsupportedOperationException(); // } // // @Override // public Directory getDir(String path) throws PathNotExist { // throw new UnsupportedOperationException(); // } // // @Override // public Map<String, Directory> getDirs() { // return getDirs(false); // } // // @Override // public Map<String, Directory> getDirs(boolean recursive) { // throw new UnsupportedOperationException(); // } // // @Override // public InputStream getFileInput(String path) throws PathNotExist, // DirectoryException { // if (getRemoved().contains(path)) { // throw new PathNotExist(path); // } // if (getChanges().containsFile(path)) { // return getChanges().getFileInput(path); // } // return getOriginal().getFileInput(path); // } // // @Override // public OutputStream getFileOutput(String path) throws DirectoryException { // getRemoved().remove(path); // return getChanges().getFileOutput(path); // } // // @Override // public Set<String> getFiles() { // return getFiles(false); // } // // @Override // public Set<String> getFiles(boolean recursive) { // Set<String> files = new LinkedHashSet<String>(getOriginal().getFiles(recursive)); // files.addAll(getChanges().getFiles(recursive)); // files.removeAll(getRemoved()); // return files; // } // // @Override // public boolean removeFile(String path) { // if(! containsFile(path)) { // return false; // } // // getChanges().removeFile(path); // getRemoved().add(path); // return true; // } // //}
zztobat-apktool
brut.j.dir/src/main/java/brut/directory/ChangesWrapperDirectory.java
Java
asf20
3,828
/** * Copyright 2010 Ryszard Wiśniewski <brut.alll@gmail.com> * * 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 brut.directory; import java.io.*; import java.util.Map; import java.util.Set; public interface Directory { public Set<String> getFiles(); public Set<String> getFiles(boolean recursive); public Map<String, Directory> getDirs(); public Map<String, Directory> getDirs(boolean recursive); public boolean containsFile(String path); public boolean containsDir(String path); public InputStream getFileInput(String path) throws DirectoryException; public OutputStream getFileOutput(String path) throws DirectoryException; public Directory getDir(String path) throws PathNotExist; public Directory createDir(String path) throws DirectoryException; public boolean removeFile(String path); public void copyToDir(Directory out) throws DirectoryException; public void copyToDir(Directory out, String[] fileNames) throws DirectoryException; public void copyToDir(Directory out, String fileName) throws DirectoryException; public void copyToDir(File out) throws DirectoryException; public void copyToDir(File out, String[] fileNames) throws DirectoryException; public void copyToDir(File out, String fileName) throws DirectoryException; public final char separator = '/'; }
zztobat-apktool
brut.j.dir/src/main/java/brut/directory/Directory.java
Java
asf20
1,928
/** * Copyright 2010 Ryszard Wiśniewski <brut.alll@gmail.com> * * 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 brut.directory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class ZipRODirectory extends AbstractDirectory { private ZipFile mZipFile; private String mPath; public ZipRODirectory(String zipFileName) throws DirectoryException { this(zipFileName, ""); } public ZipRODirectory(File zipFile) throws DirectoryException { this(zipFile, ""); } public ZipRODirectory(ZipFile zipFile) { this(zipFile, ""); } public ZipRODirectory(String zipFileName, String path) throws DirectoryException { this(new File(zipFileName), path); } public ZipRODirectory(File zipFile, String path) throws DirectoryException { super(); try { mZipFile = new ZipFile(zipFile); } catch (IOException e) { throw new DirectoryException(e); } mPath = path; } public ZipRODirectory(ZipFile zipFile, String path) { super(); mZipFile = zipFile; mPath = path; } @Override protected AbstractDirectory createDirLocal(String name) throws DirectoryException { throw new UnsupportedOperationException(); } @Override protected InputStream getFileInputLocal(String name) throws DirectoryException { try { return getZipFile().getInputStream(new ZipEntry(getPath() + name)); } catch (IOException e) { throw new PathNotExist(name, e); } } @Override protected OutputStream getFileOutputLocal(String name) throws DirectoryException { throw new UnsupportedOperationException(); } @Override protected void loadDirs() { loadAll(); } @Override protected void loadFiles() { loadAll(); } @Override protected void removeFileLocal(String name) { throw new UnsupportedOperationException(); } private void loadAll() { mFiles = new LinkedHashSet<String>(); mDirs = new LinkedHashMap<String, AbstractDirectory>(); int prefixLen = getPath().length(); Enumeration<? extends ZipEntry> entries = getZipFile().entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String name = entry.getName(); if (name.equals(getPath()) || ! name.startsWith(getPath())) { continue; } String subname = name.substring(prefixLen); int pos = subname.indexOf(separator); if (pos == -1) { if (! entry.isDirectory()) { mFiles.add(subname); continue; } } else { subname = subname.substring(0, pos); } if (! mDirs.containsKey(subname)) { AbstractDirectory dir = new ZipRODirectory(getZipFile(), getPath() + subname + separator); mDirs.put(subname, dir); } } } private String getPath() { return mPath; } private ZipFile getZipFile() { return mZipFile; } }
zztobat-apktool
brut.j.dir/src/main/java/brut/directory/ZipRODirectory.java
Java
asf20
4,098
/** * Copyright 2010 Ryszard Wiśniewski <brut.alll@gmail.com> * * 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 brut.directory; import brut.common.BrutException; import brut.util.BrutIO; import brut.util.OS; import java.io.*; /** * @author Ryszard Wiśniewski <brut.alll@gmail.com> */ public class DirUtil { public static void copyToDir(Directory in, Directory out) throws DirectoryException { for (String fileName : in.getFiles(true)) { copyToDir(in, out, fileName); } } public static void copyToDir(Directory in, Directory out, String[] fileNames) throws DirectoryException { for (int i = 0; i < fileNames.length; i++) { copyToDir(in, out, fileNames[i]); } } public static void copyToDir(Directory in, Directory out, String fileName) throws DirectoryException { try { if (in.containsDir(fileName)) { // TODO: remove before copying in.getDir(fileName).copyToDir(out.createDir(fileName)); } else { BrutIO.copyAndClose(in.getFileInput(fileName), out.getFileOutput(fileName)); } } catch (IOException ex) { throw new DirectoryException( "Error copying file: " + fileName, ex); } } public static void copyToDir(Directory in, File out) throws DirectoryException { for (String fileName : in.getFiles(true)) { copyToDir(in, out, fileName); } } public static void copyToDir(Directory in, File out, String[] fileNames) throws DirectoryException { for (int i = 0; i < fileNames.length; i++) { copyToDir(in, out, fileNames[i]); } } public static void copyToDir(Directory in, File out, String fileName) throws DirectoryException { try { if (in.containsDir(fileName)) { OS.rmdir(new File(out, fileName)); in.getDir(fileName).copyToDir(new File(out, fileName)); } else { File outFile = new File(out, fileName); outFile.getParentFile().mkdirs(); BrutIO.copyAndClose(in.getFileInput(fileName), new FileOutputStream(outFile)); } } catch (IOException ex) { throw new DirectoryException( "Error copying file: " + fileName, ex); } catch (BrutException ex) { throw new DirectoryException( "Error copying file: " + fileName, ex); } } }
zztobat-apktool
brut.j.dir/src/main/java/brut/directory/DirUtil.java
Java
asf20
3,169
/** * Copyright 2010 Ryszard Wiśniewski <brut.alll@gmail.com> * * 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 brut.directory; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; public abstract class AbstractDirectory implements Directory { protected Set<String> mFiles; protected Map<String, AbstractDirectory> mDirs; @Override public Set<String> getFiles() { return getFiles(false); } @Override public Set<String> getFiles(boolean recursive) { if (mFiles == null) { loadFiles(); } if (!recursive) { return mFiles; } Set<String> files = new LinkedHashSet<String>(mFiles); for (Map.Entry<String, ? extends Directory> dir : getAbstractDirs().entrySet()) { for (String path : dir.getValue().getFiles(true)) { files.add(dir.getKey() + separator + path); } } return files; } @Override public boolean containsFile(String path) { SubPath subpath; try { subpath = getSubPath(path); } catch (PathNotExist e) { return false; } if (subpath.dir != null) { return subpath.dir.containsFile(subpath.path); } return getFiles().contains(subpath.path); } @Override public boolean containsDir(String path) { SubPath subpath; try { subpath = getSubPath(path); } catch (PathNotExist e) { return false; } if (subpath.dir != null) { return subpath.dir.containsDir(subpath.path); } return getAbstractDirs().containsKey(subpath.path); } @Override public Map<String, Directory> getDirs() throws UnsupportedOperationException { return getDirs(false); } @Override public Map<String, Directory> getDirs(boolean recursive) throws UnsupportedOperationException { return new LinkedHashMap<String, Directory>(getAbstractDirs(recursive)); } @Override public InputStream getFileInput(String path) throws DirectoryException { SubPath subpath = getSubPath(path); if (subpath.dir != null) { return subpath.dir.getFileInput(subpath.path); } if (! getFiles().contains(subpath.path)) { throw new PathNotExist(path); } return getFileInputLocal(subpath.path); } @Override public OutputStream getFileOutput(String path) throws DirectoryException { ParsedPath parsed = parsePath(path); if (parsed.dir == null) { getFiles().add(parsed.subpath); return getFileOutputLocal(parsed.subpath); } Directory dir; // IMPOSSIBLE_EXCEPTION try { dir = createDir(parsed.dir); } catch (PathAlreadyExists e) { dir = getAbstractDirs().get(parsed.dir); } return dir.getFileOutput(parsed.subpath); } @Override public Directory getDir(String path) throws PathNotExist { SubPath subpath = getSubPath(path); if (subpath.dir != null) { return subpath.dir.getDir(subpath.path); } if (! getAbstractDirs().containsKey(subpath.path)) { throw new PathNotExist(path); } return getAbstractDirs().get(subpath.path); } @Override public Directory createDir(String path) throws DirectoryException { ParsedPath parsed = parsePath(path); AbstractDirectory dir; if (parsed.dir == null) { if (getAbstractDirs().containsKey(parsed.subpath)) { throw new PathAlreadyExists(path); } dir = createDirLocal(parsed.subpath); getAbstractDirs().put(parsed.subpath, dir); return dir; } if (getAbstractDirs().containsKey(parsed.dir)) { dir = getAbstractDirs().get(parsed.dir); } else { dir = createDirLocal(parsed.dir); getAbstractDirs().put(parsed.dir, dir); } return dir.createDir(parsed.subpath); } @Override public boolean removeFile(String path) { SubPath subpath; try { subpath = getSubPath(path); } catch (PathNotExist e) { return false; } if (subpath.dir != null) { return subpath.dir.removeFile(subpath.path); } if (! getFiles().contains(subpath.path)) { return false; } removeFileLocal(subpath.path); getFiles().remove(subpath.path); return true; } public void copyToDir(Directory out) throws DirectoryException { DirUtil.copyToDir(out, out); } public void copyToDir(Directory out, String[] fileNames) throws DirectoryException { DirUtil.copyToDir(out, out, fileNames); } public void copyToDir(Directory out, String fileName) throws DirectoryException { DirUtil.copyToDir(out, out, fileName); } public void copyToDir(File out) throws DirectoryException { DirUtil.copyToDir(this, out); } public void copyToDir(File out, String[] fileNames) throws DirectoryException { DirUtil.copyToDir(this, out, fileNames); } public void copyToDir(File out, String fileName) throws DirectoryException { DirUtil.copyToDir(this, out, fileName); } protected Map<String, AbstractDirectory> getAbstractDirs() { return getAbstractDirs(false); } protected Map<String, AbstractDirectory> getAbstractDirs(boolean recursive) { if (mDirs == null) { loadDirs(); } if (!recursive) { return mDirs; } Map<String, AbstractDirectory> dirs = new LinkedHashMap<String, AbstractDirectory>(mDirs); for (Map.Entry<String, AbstractDirectory> dir : getAbstractDirs().entrySet()) { for (Map.Entry<String, AbstractDirectory> subdir : dir.getValue().getAbstractDirs( true).entrySet()) { dirs.put(dir.getKey() + separator + subdir.getKey(), subdir.getValue()); } } return dirs; } private SubPath getSubPath(String path) throws PathNotExist { ParsedPath parsed = parsePath(path); if (parsed.dir == null) { return new SubPath(null, parsed.subpath); } if (! getAbstractDirs().containsKey(parsed.dir)) { throw new PathNotExist(path); } return new SubPath(getAbstractDirs().get(parsed.dir), parsed.subpath); } private ParsedPath parsePath(String path) { int pos = path.indexOf(separator); if (pos == -1) { return new ParsedPath(null, path); } return new ParsedPath(path.substring(0, pos), path.substring(pos + 1)); } abstract protected void loadFiles(); abstract protected void loadDirs(); abstract protected InputStream getFileInputLocal(String name) throws DirectoryException; abstract protected OutputStream getFileOutputLocal(String name) throws DirectoryException; abstract protected AbstractDirectory createDirLocal(String name) throws DirectoryException; abstract protected void removeFileLocal(String name); private class ParsedPath { public String dir; public String subpath; public ParsedPath(String dir, String subpath) { this.dir = dir; this.subpath = subpath; } } private class SubPath { public AbstractDirectory dir; public String path; public SubPath(AbstractDirectory dir, String path) { this.dir = dir; this.path = path; } } }
zztobat-apktool
brut.j.dir/src/main/java/brut/directory/AbstractDirectory.java
Java
asf20
8,585
/** * Copyright 2010 Ryszard Wiśniewski <brut.alll@gmail.com> * * 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 brut.directory; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.LinkedHashMap; import java.util.LinkedHashSet; public class FileDirectory extends AbstractDirectory { private File mDir; public FileDirectory(String dir) throws DirectoryException { this(new File(dir)); } public FileDirectory(File dir) throws DirectoryException { super(); if (! dir.isDirectory()) { throw new DirectoryException("file must be a directory: " + dir); } mDir = dir; } @Override protected AbstractDirectory createDirLocal(String name) throws DirectoryException { File dir = new File(generatePath(name)); dir.mkdir(); return new FileDirectory(dir); } @Override protected InputStream getFileInputLocal(String name) throws DirectoryException { try { return new FileInputStream(generatePath(name)); } catch (FileNotFoundException e) { throw new DirectoryException(e); } } @Override protected OutputStream getFileOutputLocal(String name) throws DirectoryException { try { return new FileOutputStream(generatePath(name)); } catch (FileNotFoundException e) { throw new DirectoryException(e); } } @Override protected void loadDirs() { loadAll(); } @Override protected void loadFiles() { loadAll(); } @Override protected void removeFileLocal(String name) { new File(generatePath(name)).delete(); } private String generatePath(String name) { return getDir().getPath() + separator + name; } private void loadAll() { mFiles = new LinkedHashSet<String>(); mDirs = new LinkedHashMap<String, AbstractDirectory>(); File[] files = getDir().listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isFile()) { mFiles.add(file.getName()); } else { // IMPOSSIBLE_EXCEPTION try { mDirs.put(file.getName(), new FileDirectory(file)); } catch (DirectoryException e) {} } } } private File getDir() { return mDir; } }
zztobat-apktool
brut.j.dir/src/main/java/brut/directory/FileDirectory.java
Java
asf20
3,119
/** * Copyright 2010 Ryszard Wiśniewski <brut.alll@gmail.com> * * 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 brut.directory; public class PathNotExist extends DirectoryException { public PathNotExist() { super(); } public PathNotExist(String detailMessage, Throwable throwable) { super(detailMessage, throwable); } public PathNotExist(String detailMessage) { super(detailMessage); } public PathNotExist(Throwable throwable) { super(throwable); } private static final long serialVersionUID = -6949242015506342032L; }
zztobat-apktool
brut.j.dir/src/main/java/brut/directory/PathNotExist.java
Java
asf20
1,126
/** * Copyright 2010 Ryszard Wiśniewski <brut.alll@gmail.com> * * 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 brut.common; /** * @author Ryszard Wiśniewski <brut.alll@gmail.com> */ public class BrutException extends Exception { public BrutException(Throwable cause) { super(cause); } public BrutException(String message, Throwable cause) { super(message, cause); } public BrutException(String message) { super(message); } public BrutException() { } }
zztobat-apktool
brut.j.common/src/main/java/brut/common/BrutException.java
Java
asf20
1,050
package org.xmlpull.mxp1_serializer; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import org.xmlpull.v1.XmlSerializer; /** * Implementation of XmlSerializer interface from XmlPull V1 API. This * implementation is optimzied for performance and low memory footprint. * * <p> * Implemented features: * <ul> * <li>FEATURE_NAMES_INTERNED - when enabled all returned names (namespaces, * prefixes) will be interned and it is required that all names passed as * arguments MUST be interned * <li>FEATURE_SERIALIZER_ATTVALUE_USE_APOSTROPHE * </ul> * <p> * Implemented properties: * <ul> * <li>PROPERTY_SERIALIZER_INDENTATION * <li>PROPERTY_SERIALIZER_LINE_SEPARATOR * </ul> * */ public class MXSerializer implements XmlSerializer { protected final static String XML_URI = "http://www.w3.org/XML/1998/namespace"; protected final static String XMLNS_URI = "http://www.w3.org/2000/xmlns/"; private static final boolean TRACE_SIZING = false; private static final boolean TRACE_ESCAPING = false; protected final String FEATURE_SERIALIZER_ATTVALUE_USE_APOSTROPHE = "http://xmlpull.org/v1/doc/features.html#serializer-attvalue-use-apostrophe"; protected final String FEATURE_NAMES_INTERNED = "http://xmlpull.org/v1/doc/features.html#names-interned"; protected final String PROPERTY_SERIALIZER_INDENTATION = "http://xmlpull.org/v1/doc/properties.html#serializer-indentation"; protected final String PROPERTY_SERIALIZER_LINE_SEPARATOR = "http://xmlpull.org/v1/doc/properties.html#serializer-line-separator"; protected final static String PROPERTY_LOCATION = "http://xmlpull.org/v1/doc/properties.html#location"; // properties/features protected boolean namesInterned; protected boolean attributeUseApostrophe; protected String indentationString = null; // " "; protected String lineSeparator = "\n"; protected String location; protected Writer out; protected int autoDeclaredPrefixes; protected int depth = 0; // element stack protected String elNamespace[] = new String[2]; protected String elName[] = new String[elNamespace.length]; protected String elPrefix[] = new String[elNamespace.length]; protected int elNamespaceCount[] = new int[elNamespace.length]; // namespace stack protected int namespaceEnd = 0; protected String namespacePrefix[] = new String[8]; protected String namespaceUri[] = new String[namespacePrefix.length]; protected boolean finished; protected boolean pastRoot; protected boolean setPrefixCalled; protected boolean startTagIncomplete; protected boolean doIndent; protected boolean seenTag; protected boolean seenBracket; protected boolean seenBracketBracket; // buffer output if neede to write escaped String see text(String) private static final int BUF_LEN = Runtime.getRuntime().freeMemory() > 1000000L ? 8 * 1024 : 256; protected char buf[] = new char[BUF_LEN]; protected static final String precomputedPrefixes[]; static { precomputedPrefixes = new String[32]; // arbitrary number ... for (int i = 0; i < precomputedPrefixes.length; i++) { precomputedPrefixes[i] = ("n" + i).intern(); } } private boolean checkNamesInterned = false; private void checkInterning(String name) { if (namesInterned && name != name.intern()) { throw new IllegalArgumentException( "all names passed as arguments must be interned" + "when NAMES INTERNED feature is enabled"); } } protected void reset() { location = null; out = null; autoDeclaredPrefixes = 0; depth = 0; // nullify references on all levels to allow it to be GCed for (int i = 0; i < elNamespaceCount.length; i++) { elName[i] = null; elPrefix[i] = null; elNamespace[i] = null; elNamespaceCount[i] = 2; } namespaceEnd = 0; // NOTE: no need to intern() as all literal strings and string-valued // constant expressions // are interned. String literals are defined in 3.10.5 of the Java // Language Specification // just checking ... // assert "xmlns" == "xmlns".intern(); // assert XMLNS_URI == XMLNS_URI.intern(); // TODO: how to prevent from reporting this namespace? // this is special namespace declared for consistensy with XML infoset namespacePrefix[namespaceEnd] = "xmlns"; namespaceUri[namespaceEnd] = XMLNS_URI; ++namespaceEnd; namespacePrefix[namespaceEnd] = "xml"; namespaceUri[namespaceEnd] = XML_URI; ++namespaceEnd; finished = false; pastRoot = false; setPrefixCalled = false; startTagIncomplete = false; // doIntent is not changed seenTag = false; seenBracket = false; seenBracketBracket = false; } protected void ensureElementsCapacity() { final int elStackSize = elName.length; // assert (depth + 1) >= elName.length; // we add at least one extra slot ... final int newSize = (depth >= 7 ? 2 * depth : 8) + 2; // = lucky 7 + 1 // //25 if (TRACE_SIZING) { System.err.println(getClass().getName() + " elStackSize " + elStackSize + " ==> " + newSize); } final boolean needsCopying = elStackSize > 0; String[] arr = null; // reuse arr local variable slot arr = new String[newSize]; if (needsCopying) System.arraycopy(elName, 0, arr, 0, elStackSize); elName = arr; arr = new String[newSize]; if (needsCopying) System.arraycopy(elPrefix, 0, arr, 0, elStackSize); elPrefix = arr; arr = new String[newSize]; if (needsCopying) System.arraycopy(elNamespace, 0, arr, 0, elStackSize); elNamespace = arr; final int[] iarr = new int[newSize]; if (needsCopying) { System.arraycopy(elNamespaceCount, 0, iarr, 0, elStackSize); } else { // special initialization iarr[0] = 0; } elNamespaceCount = iarr; } protected void ensureNamespacesCapacity() { // int size) { // int namespaceSize = namespacePrefix != null ? namespacePrefix.length // : 0; // assert (namespaceEnd >= namespacePrefix.length); // if(size >= namespaceSize) { // int newSize = size > 7 ? 2 * size : 8; // = lucky 7 + 1 //25 final int newSize = namespaceEnd > 7 ? 2 * namespaceEnd : 8; if (TRACE_SIZING) { System.err.println(getClass().getName() + " namespaceSize " + namespacePrefix.length + " ==> " + newSize); } final String[] newNamespacePrefix = new String[newSize]; final String[] newNamespaceUri = new String[newSize]; if (namespacePrefix != null) { System.arraycopy(namespacePrefix, 0, newNamespacePrefix, 0, namespaceEnd); System.arraycopy(namespaceUri, 0, newNamespaceUri, 0, namespaceEnd); } namespacePrefix = newNamespacePrefix; namespaceUri = newNamespaceUri; // TODO use hashes for quick namespace->prefix lookups // if( ! allStringsInterned ) { // int[] newNamespacePrefixHash = new int[newSize]; // if(namespacePrefixHash != null) { // System.arraycopy( // namespacePrefixHash, 0, newNamespacePrefixHash, 0, namespaceEnd); // } // namespacePrefixHash = newNamespacePrefixHash; // } // prefixesSize = newSize; // ////assert nsPrefixes.length > size && nsPrefixes.length == newSize // } } @Override public void setFeature(String name, boolean state) throws IllegalArgumentException, IllegalStateException { if (name == null) { throw new IllegalArgumentException("feature name can not be null"); } if (FEATURE_NAMES_INTERNED.equals(name)) { namesInterned = state; } else if (FEATURE_SERIALIZER_ATTVALUE_USE_APOSTROPHE.equals(name)) { attributeUseApostrophe = state; } else { throw new IllegalStateException("unsupported feature " + name); } } @Override public boolean getFeature(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException("feature name can not be null"); } if (FEATURE_NAMES_INTERNED.equals(name)) { return namesInterned; } else if (FEATURE_SERIALIZER_ATTVALUE_USE_APOSTROPHE.equals(name)) { return attributeUseApostrophe; } else { return false; } } // precomputed variables to simplify writing indentation protected int offsetNewLine; protected int indentationJump; protected char[] indentationBuf; protected int maxIndentLevel; protected boolean writeLineSepartor; // should end-of-line be written protected boolean writeIndentation; // is indentation used? /** * For maximum efficiency when writing indents the required output is * pre-computed This is internal function that recomputes buffer after user * requested chnages. */ protected void rebuildIndentationBuf() { if (doIndent == false) return; final int maxIndent = 65; // hardcoded maximum indentation size in // characters int bufSize = 0; offsetNewLine = 0; if (writeLineSepartor) { offsetNewLine = lineSeparator.length(); bufSize += offsetNewLine; } maxIndentLevel = 0; if (writeIndentation) { indentationJump = indentationString.length(); maxIndentLevel = maxIndent / indentationJump; bufSize += maxIndentLevel * indentationJump; } if (indentationBuf == null || indentationBuf.length < bufSize) { indentationBuf = new char[bufSize + 8]; } int bufPos = 0; if (writeLineSepartor) { for (int i = 0; i < lineSeparator.length(); i++) { indentationBuf[bufPos++] = lineSeparator.charAt(i); } } if (writeIndentation) { for (int i = 0; i < maxIndentLevel; i++) { for (int j = 0; j < indentationString.length(); j++) { indentationBuf[bufPos++] = indentationString.charAt(j); } } } } // if(doIndent) writeIndent(); protected void writeIndent() throws IOException { final int start = writeLineSepartor ? 0 : offsetNewLine; final int level = (depth > maxIndentLevel) ? maxIndentLevel : depth; out.write(indentationBuf, start, ((level - 1) * indentationJump) + offsetNewLine); } @Override public void setProperty(String name, Object value) throws IllegalArgumentException, IllegalStateException { if (name == null) { throw new IllegalArgumentException("property name can not be null"); } if (PROPERTY_SERIALIZER_INDENTATION.equals(name)) { indentationString = (String) value; } else if (PROPERTY_SERIALIZER_LINE_SEPARATOR.equals(name)) { lineSeparator = (String) value; } else if (PROPERTY_LOCATION.equals(name)) { location = (String) value; } else { throw new IllegalStateException("unsupported property " + name); } writeLineSepartor = lineSeparator != null && lineSeparator.length() > 0; writeIndentation = indentationString != null && indentationString.length() > 0; // optimize - do not write when nothing to write ... doIndent = indentationString != null && (writeLineSepartor || writeIndentation); // NOTE: when indentationString == null there is no indentation // (even though writeLineSeparator may be true ...) rebuildIndentationBuf(); seenTag = false; // for consistency } @Override public Object getProperty(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException("property name can not be null"); } if (PROPERTY_SERIALIZER_INDENTATION.equals(name)) { return indentationString; } else if (PROPERTY_SERIALIZER_LINE_SEPARATOR.equals(name)) { return lineSeparator; } else if (PROPERTY_LOCATION.equals(name)) { return location; } else { return null; } } private String getLocation() { return location != null ? " @" + location : ""; } // this is special method that can be accessed directly to retrieve Writer // serializer is using public Writer getWriter() { return out; } @Override public void setOutput(Writer writer) { reset(); out = writer; } @Override public void setOutput(OutputStream os, String encoding) throws IOException { if (os == null) throw new IllegalArgumentException("output stream can not be null"); reset(); if (encoding != null) { out = new OutputStreamWriter(os, encoding); } else { out = new OutputStreamWriter(os); } } @Override public void startDocument(String encoding, Boolean standalone) throws IOException { char apos = attributeUseApostrophe ? '\'' : '"'; if (attributeUseApostrophe) { out.write("<?xml version='1.0'"); } else { out.write("<?xml version=\"1.0\""); } if (encoding != null) { out.write(" encoding="); out.write(attributeUseApostrophe ? '\'' : '"'); out.write(encoding); out.write(attributeUseApostrophe ? '\'' : '"'); // out.write('\''); } if (standalone != null) { out.write(" standalone="); out.write(attributeUseApostrophe ? '\'' : '"'); if (standalone.booleanValue()) { out.write("yes"); } else { out.write("no"); } out.write(attributeUseApostrophe ? '\'' : '"'); // if(standalone.booleanValue()) { // out.write(" standalone='yes'"); // } else { // out.write(" standalone='no'"); // } } out.write("?>"); } @Override public void endDocument() throws IOException { // close all unclosed tag; while (depth > 0) { endTag(elNamespace[depth], elName[depth]); } // assert depth == 0; // assert startTagIncomplete == false; finished = pastRoot = startTagIncomplete = true; out.flush(); } @Override public void setPrefix(String prefix, String namespace) throws IOException { if (startTagIncomplete) closeStartTag(); // assert prefix != null; // assert namespace != null; if (prefix == null) { prefix = ""; } if (!namesInterned) { prefix = prefix.intern(); // will throw NPE if prefix==null } else if (checkNamesInterned) { checkInterning(prefix); } else if (prefix == null) { throw new IllegalArgumentException("prefix must be not null" + getLocation()); } // check that prefix is not duplicated ... for (int i = elNamespaceCount[depth]; i < namespaceEnd; i++) { if (prefix == namespacePrefix[i]) { throw new IllegalStateException("duplicated prefix " + printable(prefix) + getLocation()); } } if (!namesInterned) { namespace = namespace.intern(); } else if (checkNamesInterned) { checkInterning(namespace); } else if (namespace == null) { throw new IllegalArgumentException("namespace must be not null" + getLocation()); } if (namespaceEnd >= namespacePrefix.length) { ensureNamespacesCapacity(); } namespacePrefix[namespaceEnd] = prefix; namespaceUri[namespaceEnd] = namespace; ++namespaceEnd; setPrefixCalled = true; } protected String lookupOrDeclarePrefix(String namespace) { return getPrefix(namespace, true); } @Override public String getPrefix(String namespace, boolean generatePrefix) { return getPrefix(namespace, generatePrefix, false); } protected String getPrefix(String namespace, boolean generatePrefix, boolean nonEmpty) { // assert namespace != null; if (!namesInterned) { // when String is interned we can do much faster namespace stack // lookups ... namespace = namespace.intern(); } else if (checkNamesInterned) { checkInterning(namespace); // assert namespace != namespace.intern(); } if (namespace == null) { throw new IllegalArgumentException("namespace must be not null" + getLocation()); } else if (namespace.length() == 0) { throw new IllegalArgumentException( "default namespace cannot have prefix" + getLocation()); } // first check if namespace is already in scope for (int i = namespaceEnd - 1; i >= 0; --i) { if (namespace == namespaceUri[i]) { final String prefix = namespacePrefix[i]; if (nonEmpty && prefix.length() == 0) continue; // now check that prefix is still in scope for (int p = namespaceEnd - 1; p > i; --p) { if (prefix == namespacePrefix[p]) continue; // too bad - prefix is redeclared with // different namespace } return prefix; } } // so not found it ... if (!generatePrefix) { return null; } return generatePrefix(namespace); } private String generatePrefix(String namespace) { // assert namespace == namespace.intern(); while (true) { ++autoDeclaredPrefixes; // fast lookup uses table that was pre-initialized in static{} .... final String prefix = autoDeclaredPrefixes < precomputedPrefixes.length ? precomputedPrefixes[autoDeclaredPrefixes] : ("n" + autoDeclaredPrefixes).intern(); // make sure this prefix is not declared in any scope (avoid hiding // in-scope prefixes)! for (int i = namespaceEnd - 1; i >= 0; --i) { if (prefix == namespacePrefix[i]) { continue; // prefix is already declared - generate new and // try again } } // declare prefix if (namespaceEnd >= namespacePrefix.length) { ensureNamespacesCapacity(); } namespacePrefix[namespaceEnd] = prefix; namespaceUri[namespaceEnd] = namespace; ++namespaceEnd; return prefix; } } @Override public int getDepth() { return depth; } @Override public String getNamespace() { return elNamespace[depth]; } @Override public String getName() { return elName[depth]; } @Override public XmlSerializer startTag(String namespace, String name) throws IOException { if (startTagIncomplete) { closeStartTag(); } seenBracket = seenBracketBracket = false; ++depth; if (doIndent && depth > 0 && seenTag) { writeIndent(); } seenTag = true; setPrefixCalled = false; startTagIncomplete = true; if ((depth + 1) >= elName.length) { ensureElementsCapacity(); } // //assert namespace != null; if (checkNamesInterned && namesInterned) checkInterning(namespace); elNamespace[depth] = (namesInterned || namespace == null) ? namespace : namespace.intern(); // assert name != null; // elName[ depth ] = name; if (checkNamesInterned && namesInterned) checkInterning(name); elName[depth] = (namesInterned || name == null) ? name : name.intern(); if (out == null) { throw new IllegalStateException( "setOutput() must called set before serialization can start"); } out.write('<'); if (namespace != null) { if (namespace.length() > 0) { // ALEK: in future make this algo a feature on serializer String prefix = null; if (depth > 0 && (namespaceEnd - elNamespaceCount[depth - 1]) == 1) { // if only one prefix was declared un-declare it if the // prefix is already declared on parent el with the same URI String uri = namespaceUri[namespaceEnd - 1]; if (uri == namespace || uri.equals(namespace)) { String elPfx = namespacePrefix[namespaceEnd - 1]; // 2 == to skip predefined namesapces (xml and xmlns // ...) for (int pos = elNamespaceCount[depth - 1] - 1; pos >= 2; --pos) { String pf = namespacePrefix[pos]; if (pf == elPfx || pf.equals(elPfx)) { String n = namespaceUri[pos]; if (n == uri || n.equals(uri)) { --namespaceEnd; // un-declare namespace: // this is kludge! prefix = elPfx; } break; } } } } if (prefix == null) { prefix = lookupOrDeclarePrefix(namespace); } // assert prefix != null; // make sure that default ("") namespace to not print ":" if (prefix.length() > 0) { elPrefix[depth] = prefix; out.write(prefix); out.write(':'); } else { elPrefix[depth] = ""; } } else { // make sure that default namespace can be declared for (int i = namespaceEnd - 1; i >= 0; --i) { if (namespacePrefix[i] == "") { final String uri = namespaceUri[i]; if (uri == null) { // declare default namespace setPrefix("", ""); } else if (uri.length() > 0) { throw new IllegalStateException( "start tag can not be written in empty default namespace " + "as default namespace is currently bound to '" + uri + "'" + getLocation()); } break; } } elPrefix[depth] = ""; } } else { elPrefix[depth] = ""; } out.write(name); return this; } @Override public XmlSerializer attribute(String namespace, String name, String value) throws IOException { if (!startTagIncomplete) { throw new IllegalArgumentException( "startTag() must be called before attribute()" + getLocation()); } // assert setPrefixCalled == false; out.write(' '); // //assert namespace != null; if (namespace != null && namespace.length() > 0) { // namespace = namespace.intern(); if (!namesInterned) { namespace = namespace.intern(); } else if (checkNamesInterned) { checkInterning(namespace); } String prefix = getPrefix(namespace, false, true); // assert( prefix != null); // if(prefix.length() == 0) { if (prefix == null) { // needs to declare prefix to hold default namespace // NOTE: attributes such as a='b' are in NO namespace prefix = generatePrefix(namespace); } out.write(prefix); out.write(':'); // if(prefix.length() > 0) { // out.write(prefix); // out.write(':'); // } } // assert name != null; out.write(name); out.write('='); // assert value != null; out.write(attributeUseApostrophe ? '\'' : '"'); writeAttributeValue(value, out); out.write(attributeUseApostrophe ? '\'' : '"'); return this; } protected void closeStartTag() throws IOException { if (finished) { throw new IllegalArgumentException( "trying to write past already finished output" + getLocation()); } if (seenBracket) { seenBracket = seenBracketBracket = false; } if (startTagIncomplete || setPrefixCalled) { if (setPrefixCalled) { throw new IllegalArgumentException( "startTag() must be called immediately after setPrefix()" + getLocation()); } if (!startTagIncomplete) { throw new IllegalArgumentException( "trying to close start tag that is not opened" + getLocation()); } // write all namespace delcarations! writeNamespaceDeclarations(); out.write('>'); elNamespaceCount[depth] = namespaceEnd; startTagIncomplete = false; } } protected void writeNamespaceDeclarations() throws IOException { // int start = elNamespaceCount[ depth - 1 ]; for (int i = elNamespaceCount[depth - 1]; i < namespaceEnd; i++) { if (doIndent && namespaceUri[i].length() > 40) { writeIndent(); out.write(" "); } if (namespacePrefix[i] != "") { out.write(" xmlns:"); out.write(namespacePrefix[i]); out.write('='); } else { out.write(" xmlns="); } out.write(attributeUseApostrophe ? '\'' : '"'); // NOTE: escaping of namespace value the same way as attributes!!!! writeAttributeValue(namespaceUri[i], out); out.write(attributeUseApostrophe ? '\'' : '"'); } } @Override public XmlSerializer endTag(String namespace, String name) throws IOException { // check that level is valid // //assert namespace != null; // if(namespace != null) { // namespace = namespace.intern(); // } seenBracket = seenBracketBracket = false; if (namespace != null) { if (!namesInterned) { namespace = namespace.intern(); } else if (checkNamesInterned) { checkInterning(namespace); } } if (namespace != elNamespace[depth]) { throw new IllegalArgumentException("expected namespace " + printable(elNamespace[depth]) + " and not " + printable(namespace) + getLocation()); } if (name == null) { throw new IllegalArgumentException("end tag name can not be null" + getLocation()); } if (checkNamesInterned && namesInterned) { checkInterning(name); } String startTagName = elName[depth]; if ((!namesInterned && !name.equals(startTagName)) || (namesInterned && name != startTagName)) { throw new IllegalArgumentException("expected element name " + printable(elName[depth]) + " and not " + printable(name) + getLocation()); } if (startTagIncomplete) { writeNamespaceDeclarations(); out.write(" />"); // space is added to make it easier to work in // XHTML!!! --depth; } else { // assert startTagIncomplete == false; if (doIndent && seenTag) { writeIndent(); } out.write("</"); String startTagPrefix = elPrefix[depth]; if (startTagPrefix.length() > 0) { out.write(startTagPrefix); out.write(':'); } // if(namespace != null && namespace.length() > 0) { // //TODO prefix should be alredy known from matching start tag ... // final String prefix = lookupOrDeclarePrefix( namespace ); // //assert( prefix != null); // if(prefix.length() > 0) { // out.write(prefix); // out.write(':'); // } // } out.write(name); out.write('>'); --depth; } namespaceEnd = elNamespaceCount[depth]; startTagIncomplete = false; seenTag = true; return this; } @Override public XmlSerializer text(String text) throws IOException { // assert text != null; if (startTagIncomplete || setPrefixCalled) closeStartTag(); if (doIndent && seenTag) seenTag = false; writeElementContent(text, out); return this; } @Override public XmlSerializer text(char[] buf, int start, int len) throws IOException { if (startTagIncomplete || setPrefixCalled) closeStartTag(); if (doIndent && seenTag) seenTag = false; writeElementContent(buf, start, len, out); return this; } @Override public void cdsect(String text) throws IOException { if (startTagIncomplete || setPrefixCalled || seenBracket) closeStartTag(); if (doIndent && seenTag) seenTag = false; out.write("<![CDATA["); out.write(text); // escape? out.write("]]>"); } @Override public void entityRef(String text) throws IOException { if (startTagIncomplete || setPrefixCalled || seenBracket) closeStartTag(); if (doIndent && seenTag) seenTag = false; out.write('&'); out.write(text); // escape? out.write(';'); } @Override public void processingInstruction(String text) throws IOException { if (startTagIncomplete || setPrefixCalled || seenBracket) closeStartTag(); if (doIndent && seenTag) seenTag = false; out.write("<?"); out.write(text); // escape? out.write("?>"); } @Override public void comment(String text) throws IOException { if (startTagIncomplete || setPrefixCalled || seenBracket) closeStartTag(); if (doIndent && seenTag) seenTag = false; out.write("<!--"); out.write(text); // escape? out.write("-->"); } @Override public void docdecl(String text) throws IOException { if (startTagIncomplete || setPrefixCalled || seenBracket) closeStartTag(); if (doIndent && seenTag) seenTag = false; out.write("<!DOCTYPE"); out.write(text); // escape? out.write(">"); } @Override public void ignorableWhitespace(String text) throws IOException { if (startTagIncomplete || setPrefixCalled || seenBracket) closeStartTag(); if (doIndent && seenTag) seenTag = false; if (text.length() == 0) { throw new IllegalArgumentException( "empty string is not allowed for ignorable whitespace" + getLocation()); } out.write(text); // no escape? } @Override public void flush() throws IOException { if (!finished && startTagIncomplete) closeStartTag(); out.flush(); } // --- utility methods protected void writeAttributeValue(String value, Writer out) throws IOException { // .[apostrophe and <, & escaped], final char quot = attributeUseApostrophe ? '\'' : '"'; final String quotEntity = attributeUseApostrophe ? "&apos;" : "&quot;"; int pos = 0; for (int i = 0; i < value.length(); i++) { char ch = value.charAt(i); if (ch == '&') { if (i > pos) out.write(value.substring(pos, i)); out.write("&amp;"); pos = i + 1; } if (ch == '<') { if (i > pos) out.write(value.substring(pos, i)); out.write("&lt;"); pos = i + 1; } else if (ch == quot) { if (i > pos) out.write(value.substring(pos, i)); out.write(quotEntity); pos = i + 1; } else if (ch < 32) { // in XML 1.0 only legal character are #x9 | #xA | #xD // and they must be escaped otherwise in attribute value they // are normalized to spaces if (ch == 13 || ch == 10 || ch == 9) { if (i > pos) out.write(value.substring(pos, i)); out.write("&#"); out.write(Integer.toString(ch)); out.write(';'); pos = i + 1; } else { if (TRACE_ESCAPING) System.err.println(getClass().getName() + " DEBUG ATTR value.len=" + value.length() + " " + printable(value)); throw new IllegalStateException( // "character "+Integer.toString(ch)+" is not allowed in output"+getLocation()); "character " + printable(ch) + " (" + Integer.toString(ch) + ") is not allowed in output" + getLocation() + " (attr value=" + printable(value) + ")"); // in XML 1.1 legal are [#x1-#xD7FF] // if(ch > 0) { // if(i > pos) out.write(text.substring(pos, i)); // out.write("&#"); // out.write(Integer.toString(ch)); // out.write(';'); // pos = i + 1; // } else { // throw new IllegalStateException( // "character zero is not allowed in XML 1.1 output"+getLocation()); // } } } } if (pos > 0) { out.write(value.substring(pos)); } else { out.write(value); // this is shortcut to the most common case } } protected void writeElementContent(String text, Writer out) throws IOException { // esccape '<', '&', ']]>', <32 if necessary int pos = 0; for (int i = 0; i < text.length(); i++) { // TODO: check if doing char[] text.getChars() would be faster than // getCharAt(i) ... char ch = text.charAt(i); if (ch == ']') { if (seenBracket) { seenBracketBracket = true; } else { seenBracket = true; } } else { if (ch == '&') { if (i > pos) out.write(text.substring(pos, i)); out.write("&amp;"); pos = i + 1; } else if (ch == '<') { if (i > pos) out.write(text.substring(pos, i)); out.write("&lt;"); pos = i + 1; } else if (seenBracketBracket && ch == '>') { if (i > pos) out.write(text.substring(pos, i)); out.write("&gt;"); pos = i + 1; } else if (ch < 32) { // in XML 1.0 only legal character are #x9 | #xA | #xD if (ch == 9 || ch == 10 || ch == 13) { // pass through // } else if(ch == 13) { //escape // if(i > pos) out.write(text.substring(pos, i)); // out.write("&#"); // out.write(Integer.toString(ch)); // out.write(';'); // pos = i + 1; } else { if (TRACE_ESCAPING) System.err.println(getClass().getName() + " DEBUG TEXT value.len=" + text.length() + " " + printable(text)); throw new IllegalStateException("character " + Integer.toString(ch) + " is not allowed in output" + getLocation() + " (text value=" + printable(text) + ")"); // in XML 1.1 legal are [#x1-#xD7FF] // if(ch > 0) { // if(i > pos) out.write(text.substring(pos, i)); // out.write("&#"); // out.write(Integer.toString(ch)); // out.write(';'); // pos = i + 1; // } else { // throw new IllegalStateException( // "character zero is not allowed in XML 1.1 output"+getLocation()); // } } } if (seenBracket) { seenBracketBracket = seenBracket = false; } } } if (pos > 0) { out.write(text.substring(pos)); } else { out.write(text); // this is shortcut to the most common case } } protected void writeElementContent(char[] buf, int off, int len, Writer out) throws IOException { // esccape '<', '&', ']]>' final int end = off + len; int pos = off; for (int i = off; i < end; i++) { final char ch = buf[i]; if (ch == ']') { if (seenBracket) { seenBracketBracket = true; } else { seenBracket = true; } } else { if (ch == '&') { if (i > pos) { out.write(buf, pos, i - pos); } out.write("&amp;"); pos = i + 1; } else if (ch == '<') { if (i > pos) { out.write(buf, pos, i - pos); } out.write("&lt;"); pos = i + 1; } else if (seenBracketBracket && ch == '>') { if (i > pos) { out.write(buf, pos, i - pos); } out.write("&gt;"); pos = i + 1; } else if (ch < 32) { // in XML 1.0 only legal character are #x9 | #xA | #xD if (ch == 9 || ch == 10 || ch == 13) { // pass through // } else if(ch == 13 ) { //if(ch == '\r') { // if(i > pos) { // out.write(buf, pos, i - pos); // } // out.write("&#"); // out.write(Integer.toString(ch)); // out.write(';'); // pos = i + 1; } else { if (TRACE_ESCAPING) System.err.println(getClass().getName() + " DEBUG TEXT value.len=" + len + " " + printable(new String(buf, off, len))); throw new IllegalStateException("character " + printable(ch) + " (" + Integer.toString(ch) + ") is not allowed in output" + getLocation()); // in XML 1.1 legal are [#x1-#xD7FF] // if(ch > 0) { // if(i > pos) out.write(text.substring(pos, i)); // out.write("&#"); // out.write(Integer.toString(ch)); // out.write(';'); // pos = i + 1; // } else { // throw new IllegalStateException( // "character zero is not allowed in XML 1.1 output"+getLocation()); // } } } if (seenBracket) { seenBracketBracket = seenBracket = false; } // assert seenBracketBracket == seenBracket == false; } } if (end > pos) { out.write(buf, pos, end - pos); } } /** simple utility method -- good for debugging */ protected static final String printable(String s) { if (s == null) return "null"; StringBuffer retval = new StringBuffer(s.length() + 16); retval.append("'"); char ch; for (int i = 0; i < s.length(); i++) { addPrintable(retval, s.charAt(i)); } retval.append("'"); return retval.toString(); } protected static final String printable(char ch) { StringBuffer retval = new StringBuffer(); addPrintable(retval, ch); return retval.toString(); } private static void addPrintable(StringBuffer retval, char ch) { switch (ch) { case '\b': retval.append("\\b"); break; case '\t': retval.append("\\t"); break; case '\n': retval.append("\\n"); break; case '\f': retval.append("\\f"); break; case '\r': retval.append("\\r"); break; case '\"': retval.append("\\\""); break; case '\'': retval.append("\\\'"); break; case '\\': retval.append("\\\\"); break; default: if (ch < 0x20 || ch > 0x7e) { final String ss = "0000" + Integer.toString(ch, 16); retval.append("\\u" + ss.substring(ss.length() - 4, ss.length())); } else { retval.append(ch); } } } }
zztobat-apktool
brut.apktool/apktool-lib/src/main/java/org/xmlpull/mxp1_serializer/MXSerializer.java
Java
asf20
34,725
/* * Copyright (C) 2006 The Android Open Source Project * * 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 android.content.res; import org.xmlpull.v1.XmlPullParser; import android.util.AttributeSet; /** * The XML parsing interface returned for an XML resource. This is a standard * XmlPullParser interface, as well as an extended AttributeSet interface and an * additional close() method on this interface for the client to indicate when * it is done reading the resource. */ public interface XmlResourceParser extends XmlPullParser, AttributeSet { /** * Close this interface to the resource. Calls on the interface are no * longer value after this call. */ public void close(); }
zztobat-apktool
brut.apktool/apktool-lib/src/main/java/android/content/res/XmlResourceParser.java
Java
asf20
1,219
/* * Copyright (C) 2007 The Android Open Source Project * * 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 android.util; /** * Container for a dynamically typed data value. Primarily used with * {@link android.content.res.Resources} for holding resource values. */ public class TypedValue { /** The value contains no data. */ public static final int TYPE_NULL = 0x00; /** The <var>data</var> field holds a resource identifier. */ public static final int TYPE_REFERENCE = 0x01; /** * The <var>data</var> field holds an attribute resource identifier * (referencing an attribute in the current theme style, not a resource * entry). */ public static final int TYPE_ATTRIBUTE = 0x02; /** * The <var>string</var> field holds string data. In addition, if * <var>data</var> is non-zero then it is the string block index of the * string and <var>assetCookie</var> is the set of assets the string came * from. */ public static final int TYPE_STRING = 0x03; /** The <var>data</var> field holds an IEEE 754 floating point number. */ public static final int TYPE_FLOAT = 0x04; /** * The <var>data</var> field holds a complex number encoding a dimension * value. */ public static final int TYPE_DIMENSION = 0x05; /** * The <var>data</var> field holds a complex number encoding a fraction of a * container. */ public static final int TYPE_FRACTION = 0x06; /** * Identifies the start of plain integer values. Any type value from this to * {@link #TYPE_LAST_INT} means the <var>data</var> field holds a generic * integer value. */ public static final int TYPE_FIRST_INT = 0x10; /** * The <var>data</var> field holds a number that was originally specified in * decimal. */ public static final int TYPE_INT_DEC = 0x10; /** * The <var>data</var> field holds a number that was originally specified in * hexadecimal (0xn). */ public static final int TYPE_INT_HEX = 0x11; /** * The <var>data</var> field holds 0 or 1 that was originally specified as * "false" or "true". */ public static final int TYPE_INT_BOOLEAN = 0x12; /** * Identifies the start of integer values that were specified as color * constants (starting with '#'). */ public static final int TYPE_FIRST_COLOR_INT = 0x1c; /** * The <var>data</var> field holds a color that was originally specified as * #aarrggbb. */ public static final int TYPE_INT_COLOR_ARGB8 = 0x1c; /** * The <var>data</var> field holds a color that was originally specified as * #rrggbb. */ public static final int TYPE_INT_COLOR_RGB8 = 0x1d; /** * The <var>data</var> field holds a color that was originally specified as * #argb. */ public static final int TYPE_INT_COLOR_ARGB4 = 0x1e; /** * The <var>data</var> field holds a color that was originally specified as * #rgb. */ public static final int TYPE_INT_COLOR_RGB4 = 0x1f; /** * Identifies the end of integer values that were specified as color * constants. */ public static final int TYPE_LAST_COLOR_INT = 0x1f; /** Identifies the end of plain integer values. */ public static final int TYPE_LAST_INT = 0x1f; /* ------------------------------------------------------------ */ /** Complex data: bit location of unit information. */ public static final int COMPLEX_UNIT_SHIFT = 0; /** * Complex data: mask to extract unit information (after shifting by * {@link #COMPLEX_UNIT_SHIFT}). This gives us 16 possible types, as defined * below. */ public static final int COMPLEX_UNIT_MASK = 0xf; /** {@link #TYPE_DIMENSION} complex unit: Value is raw pixels. */ public static final int COMPLEX_UNIT_PX = 0; /** * {@link #TYPE_DIMENSION} complex unit: Value is Device Independent Pixels. */ public static final int COMPLEX_UNIT_DIP = 1; /** {@link #TYPE_DIMENSION} complex unit: Value is a scaled pixel. */ public static final int COMPLEX_UNIT_SP = 2; /** {@link #TYPE_DIMENSION} complex unit: Value is in points. */ public static final int COMPLEX_UNIT_PT = 3; /** {@link #TYPE_DIMENSION} complex unit: Value is in inches. */ public static final int COMPLEX_UNIT_IN = 4; /** {@link #TYPE_DIMENSION} complex unit: Value is in millimeters. */ public static final int COMPLEX_UNIT_MM = 5; /** * {@link #TYPE_FRACTION} complex unit: A basic fraction of the overall size. */ public static final int COMPLEX_UNIT_FRACTION = 0; /** {@link #TYPE_FRACTION} complex unit: A fraction of the parent size. */ public static final int COMPLEX_UNIT_FRACTION_PARENT = 1; /** * Complex data: where the radix information is, telling where the decimal * place appears in the mantissa. */ public static final int COMPLEX_RADIX_SHIFT = 4; /** * Complex data: mask to extract radix information (after shifting by * {@link #COMPLEX_RADIX_SHIFT}). This give us 4 possible fixed point * representations as defined below. */ public static final int COMPLEX_RADIX_MASK = 0x3; /** Complex data: the mantissa is an integral number -- i.e., 0xnnnnnn.0 */ public static final int COMPLEX_RADIX_23p0 = 0; /** Complex data: the mantissa magnitude is 16 bits -- i.e, 0xnnnn.nn */ public static final int COMPLEX_RADIX_16p7 = 1; /** Complex data: the mantissa magnitude is 8 bits -- i.e, 0xnn.nnnn */ public static final int COMPLEX_RADIX_8p15 = 2; /** Complex data: the mantissa magnitude is 0 bits -- i.e, 0x0.nnnnnn */ public static final int COMPLEX_RADIX_0p23 = 3; /** Complex data: bit location of mantissa information. */ public static final int COMPLEX_MANTISSA_SHIFT = 8; /** * Complex data: mask to extract mantissa information (after shifting by * {@link #COMPLEX_MANTISSA_SHIFT}). This gives us 23 bits of precision; the * top bit is the sign. */ public static final int COMPLEX_MANTISSA_MASK = 0xffffff; /* ------------------------------------------------------------ */ /** * If {@link #density} is equal to this value, then the density should be * treated as the system's default density value: * {@link DisplayMetrics#DENSITY_DEFAULT}. */ public static final int DENSITY_DEFAULT = 0; /** * If {@link #density} is equal to this value, then there is no density * associated with the resource and it should not be scaled. */ public static final int DENSITY_NONE = 0xffff; /* ------------------------------------------------------------ */ /** * The type held by this value, as defined by the constants here. This tells * you how to interpret the other fields in the object. */ public int type; private static final float MANTISSA_MULT = 1.0f / (1 << TypedValue.COMPLEX_MANTISSA_SHIFT); private static final float[] RADIX_MULTS = new float[] { 1.0f * MANTISSA_MULT, 1.0f / (1 << 7) * MANTISSA_MULT, 1.0f / (1 << 15) * MANTISSA_MULT, 1.0f / (1 << 23) * MANTISSA_MULT }; /** * Retrieve the base value from a complex data integer. This uses the * {@link #COMPLEX_MANTISSA_MASK} and {@link #COMPLEX_RADIX_MASK} fields of * the data to compute a floating point representation of the number they * describe. The units are ignored. * * @param complex * A complex data value. * * @return A floating point value corresponding to the complex data. */ public static float complexToFloat(int complex) { return (complex & (TypedValue.COMPLEX_MANTISSA_MASK << TypedValue.COMPLEX_MANTISSA_SHIFT)) * RADIX_MULTS[(complex >> TypedValue.COMPLEX_RADIX_SHIFT) & TypedValue.COMPLEX_RADIX_MASK]; } private static final String[] DIMENSION_UNIT_STRS = new String[] { "px", "dip", "sp", "pt", "in", "mm" }; private static final String[] FRACTION_UNIT_STRS = new String[] { "%", "%p" }; /** * Perform type conversion as per {@link #coerceToString()} on an explicitly * supplied type and data. * * @param type * The data type identifier. * @param data * The data value. * * @return String The coerced string value. If the value is null or the type * is not known, null is returned. */ public static final String coerceToString(int type, int data) { switch (type) { case TYPE_NULL: return null; case TYPE_REFERENCE: return "@" + data; case TYPE_ATTRIBUTE: return "?" + data; case TYPE_FLOAT: return Float.toString(Float.intBitsToFloat(data)); case TYPE_DIMENSION: return Float.toString(complexToFloat(data)) + DIMENSION_UNIT_STRS[(data >> COMPLEX_UNIT_SHIFT) & COMPLEX_UNIT_MASK]; case TYPE_FRACTION: return Float.toString(complexToFloat(data) * 100) + FRACTION_UNIT_STRS[(data >> COMPLEX_UNIT_SHIFT) & COMPLEX_UNIT_MASK]; case TYPE_INT_HEX: return "0x" + Integer.toHexString(data); case TYPE_INT_BOOLEAN: return data != 0 ? "true" : "false"; } if (type >= TYPE_FIRST_COLOR_INT && type <= TYPE_LAST_COLOR_INT) { String res = String.format("%08x", data); char[] vals = res.toCharArray(); switch (type) { default: case TYPE_INT_COLOR_ARGB8:// #AaRrGgBb break; case TYPE_INT_COLOR_RGB8:// #FFRrGgBb->#RrGgBb res = res.substring(2); break; case TYPE_INT_COLOR_ARGB4:// #AARRGGBB->#ARGB res = new StringBuffer().append(vals[0]).append(vals[2]) .append(vals[4]).append(vals[6]).toString(); break; case TYPE_INT_COLOR_RGB4:// #FFRRGGBB->#RGB res = new StringBuffer().append(vals[2]).append(vals[4]) .append(vals[6]).toString(); break; } return "#" + res; } else if (type >= TYPE_FIRST_INT && type <= TYPE_LAST_INT) { String res; switch (type) { default: case TYPE_INT_DEC: res = Integer.toString(data); break; // defined before /* * case TYPE_INT_HEX: res = "0x" + Integer.toHexString(data); break; * case TYPE_INT_BOOLEAN: res = (data != 0) ? "true":"false"; break; */ } return res; } return null; } };
zztobat-apktool
brut.apktool/apktool-lib/src/main/java/android/util/TypedValue.java
Java
asf20
10,298
/* * Copyright 2008 Android4ME * * 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 android.util; /** * @author Dmitry Skiba * */ public interface AttributeSet { int getAttributeCount(); String getAttributeName(int index); String getAttributeValue(int index); String getPositionDescription(); int getAttributeNameResource(int index); int getAttributeListValue(int index, String options[], int defaultValue); boolean getAttributeBooleanValue(int index, boolean defaultValue); int getAttributeResourceValue(int index, int defaultValue); int getAttributeIntValue(int index, int defaultValue); int getAttributeUnsignedIntValue(int index, int defaultValue); float getAttributeFloatValue(int index, float defaultValue); String getIdAttribute(); String getClassAttribute(); int getIdAttributeResourceValue(int index); int getStyleAttribute(); String getAttributeValue(String namespace, String attribute); int getAttributeListValue(String namespace, String attribute, String options[], int defaultValue); boolean getAttributeBooleanValue(String namespace, String attribute, boolean defaultValue); int getAttributeResourceValue(String namespace, String attribute, int defaultValue); int getAttributeIntValue(String namespace, String attribute, int defaultValue); int getAttributeUnsignedIntValue(String namespace, String attribute, int defaultValue); float getAttributeFloatValue(String namespace, String attribute, float defaultValue); // TODO: remove int getAttributeValueType(int index); int getAttributeValueData(int index); }
zztobat-apktool
brut.apktool/apktool-lib/src/main/java/android/util/AttributeSet.java
Java
asf20
2,186
/* * @(#)LEDataInputStream.java * * Summary: Little-Endian version of DataInputStream. * * Copyright: (c) 1998-2010 Roedy Green, Canadian Mind Products, http://mindprod.com * * Licence: This software may be copied and used freely for any purpose but military. * http://mindprod.com/contact/nonmil.html * * Requires: JDK 1.1+ * * Created with: IntelliJ IDEA IDE. * * Version History: * 1.8 2007-05-24 */ package com.mindprod.ledatastream; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; /** * Little-Endian version of DataInputStream. * <p/> * Very similar to DataInputStream except it reads little-endian instead of * big-endian binary data. We can't extend DataInputStream directly since it has * only final methods, though DataInputStream itself is not final. This forces * us implement LEDataInputStream with a DataInputStream object, and use wrapper * methods. * * @author Roedy Green, Canadian Mind Products * @version 1.8 2007-05-24 * @since 1998 */ public final class LEDataInputStream implements DataInput { // ------------------------------ CONSTANTS ------------------------------ /** * undisplayed copyright notice. * * @noinspection UnusedDeclaration */ private static final String EMBEDDED_COPYRIGHT = "copyright (c) 1999-2010 Roedy Green, Canadian Mind Products, http://mindprod.com"; // ------------------------------ FIELDS ------------------------------ /** * to get at the big-Endian methods of a basic DataInputStream * * @noinspection WeakerAccess */ protected final DataInputStream dis; /** * to get at the a basic readBytes method. * * @noinspection WeakerAccess */ protected final InputStream is; /** * work array for buffering input. * * @noinspection WeakerAccess */ protected final byte[] work; // -------------------------- PUBLIC STATIC METHODS // -------------------------- /** * Note. This is a STATIC method! * * @param in * stream to read UTF chars from (endian irrelevant) * * @return string from stream * @throws IOException * if read fails. */ public static String readUTF(DataInput in) throws IOException { return DataInputStream.readUTF(in); } // -------------------------- PUBLIC INSTANCE METHODS // -------------------------- /** * constructor. * * @param in * binary inputstream of little-endian data. */ public LEDataInputStream(InputStream in) { this.is = in; this.dis = new DataInputStream(in); work = new byte[8]; } /** * close. * * @throws IOException * if close fails. */ public final void close() throws IOException { dis.close(); } /** * Read bytes. Watch out, read may return fewer bytes than requested. * * @param ba * where the bytes go. * @param off * offset in buffer, not offset in file. * @param len * count of bytes to read. * * @return how many bytes read. * @throws IOException * if read fails. */ public final int read(byte ba[], int off, int len) throws IOException { // For efficiency, we avoid one layer of wrapper return is.read(ba, off, len); } /** * read only a one-byte boolean. * * @return true or false. * @throws IOException * if read fails. * @see java.io.DataInput#readBoolean() */ @Override public final boolean readBoolean() throws IOException { return dis.readBoolean(); } /** * read byte. * * @return the byte read. * @throws IOException * if read fails. * @see java.io.DataInput#readByte() */ @Override public final byte readByte() throws IOException { return dis.readByte(); } /** * Read on char. like DataInputStream.readChar except little endian. * * @return little endian 16-bit unicode char from the stream. * @throws IOException * if read fails. */ @Override public final char readChar() throws IOException { dis.readFully(work, 0, 2); return (char) ((work[1] & 0xff) << 8 | (work[0] & 0xff)); } /** * Read a double. like DataInputStream.readDouble except little endian. * * @return little endian IEEE double from the datastream. * @throws IOException */ @Override public final double readDouble() throws IOException { return Double.longBitsToDouble(readLong()); } /** * Read one float. Like DataInputStream.readFloat except little endian. * * @return little endian IEEE float from the datastream. * @throws IOException * if read fails. */ @Override public final float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } /** * Read bytes until the array is filled. * * @see java.io.DataInput#readFully(byte[]) */ @Override public final void readFully(byte ba[]) throws IOException { dis.readFully(ba, 0, ba.length); } /** * Read bytes until the count is satisfied. * * @throws IOException * if read fails. * @see java.io.DataInput#readFully(byte[],int,int) */ @Override public final void readFully(byte ba[], int off, int len) throws IOException { dis.readFully(ba, off, len); } /** * Read an int, 32-bits. Like DataInputStream.readInt except little endian. * * @return little-endian binary int from the datastream * @throws IOException * if read fails. */ @Override public final int readInt() throws IOException { dis.readFully(work, 0, 4); return (work[3]) << 24 | (work[2] & 0xff) << 16 | (work[1] & 0xff) << 8 | (work[0] & 0xff); } /** * Read a line. * * @return a rough approximation of the 8-bit stream as a 16-bit unicode * string * @throws IOException * @noinspection deprecation * @deprecated This method does not properly convert bytes to characters. * Use a Reader instead with a little-endian encoding. */ @Deprecated @Override public final String readLine() throws IOException { return dis.readLine(); } /** * read a long, 64-bits. Like DataInputStream.readLong except little endian. * * @return little-endian binary long from the datastream. * @throws IOException */ @Override public final long readLong() throws IOException { dis.readFully(work, 0, 8); return (long) (work[7]) << 56 | /* long cast needed or shift done modulo 32 */ (long) (work[6] & 0xff) << 48 | (long) (work[5] & 0xff) << 40 | (long) (work[4] & 0xff) << 32 | (long) (work[3] & 0xff) << 24 | (long) (work[2] & 0xff) << 16 | (long) (work[1] & 0xff) << 8 | work[0] & 0xff; } /** * Read short, 16-bits. Like DataInputStream.readShort except little endian. * * @return little endian binary short from stream. * @throws IOException * if read fails. */ @Override public final short readShort() throws IOException { dis.readFully(work, 0, 2); return (short) ((work[1] & 0xff) << 8 | (work[0] & 0xff)); } /** * Read UTF counted string. * * @return String read. */ @Override public final String readUTF() throws IOException { return dis.readUTF(); } /** * Read an unsigned byte. Note: returns an int, even though says Byte * (non-Javadoc) * * @throws IOException * if read fails. * @see java.io.DataInput#readUnsignedByte() */ @Override public final int readUnsignedByte() throws IOException { return dis.readUnsignedByte(); } /** * Read an unsigned short, 16 bits. Like DataInputStream.readUnsignedShort * except little endian. Note, returns int even though it reads a short. * * @return little-endian int from the stream. * @throws IOException * if read fails. */ @Override public final int readUnsignedShort() throws IOException { dis.readFully(work, 0, 2); return ((work[1] & 0xff) << 8 | (work[0] & 0xff)); } /** * Skip over bytes in the stream. See the general contract of the * <code>skipBytes</code> method of <code>DataInput</code>. * <p/> * Bytes for this operation are read from the contained input stream. * * @param n * the number of bytes to be skipped. * * @return the actual number of bytes skipped. * @throws IOException * if an I/O error occurs. */ @Override public final int skipBytes(int n) throws IOException { return dis.skipBytes(n); } }
zztobat-apktool
brut.apktool/apktool-lib/src/main/java/com/mindprod/ledatastream/LEDataInputStream.java
Java
asf20
8,720
/** * Copyright 2011 Ryszard Wiśniewski <brut.alll@gmail.com> * * 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 brut.androlib; import brut.common.BrutException; /** * @author Ryszard Wiśniewski <brut.alll@gmail.com> */ public class AndrolibException extends BrutException { public AndrolibException() { } public AndrolibException(String message) { super(message); } public AndrolibException(String message, Throwable cause) { super(message, cause); } public AndrolibException(Throwable cause) { super(cause); } }
zztobat-apktool
brut.apktool/apktool-lib/src/main/java/brut/androlib/AndrolibException.java
Java
asf20
1,069
/** * Copyright 2011 Ryszard Wiśniewski <brut.alll@gmail.com> * * 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 brut.androlib.mod; import java.io.Writer; /** * @author Ryszard Wiśniewski <brut.alll@gmail.com> */ public class IndentingWriter extends org.jf.util.IndentingWriter { public IndentingWriter(Writer writer) { super(writer); } }
zztobat-apktool
brut.apktool/apktool-lib/src/main/java/brut/androlib/mod/IndentingWriter.java
Java
asf20
882
/** * Copyright 2011 Ryszard Wiśniewski <brut.alll@gmail.com> * * 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 brut.androlib.mod; import java.io.*; import org.antlr.runtime.*; import org.antlr.runtime.tree.CommonTree; import org.antlr.runtime.tree.CommonTreeNodeStream; import org.jf.dexlib.DexFile; import org.jf.smali.*; /** * @author Ryszard Wiśniewski <brut.alll@gmail.com> */ public class SmaliMod { public static boolean assembleSmaliFile(InputStream smaliStream, String name, DexFile dexFile, boolean verboseErrors, boolean oldLexer, boolean printTokens) throws IOException, RecognitionException { CommonTokenStream tokens; boolean lexerErrors = false; LexerErrorInterface lexer; InputStreamReader reader = new InputStreamReader(smaliStream, "UTF-8"); lexer = new smaliFlexLexer(reader); tokens = new CommonTokenStream((TokenSource) lexer); if (printTokens) { tokens.getTokens(); for (int i = 0; i < tokens.size(); i++) { Token token = tokens.get(i); if (token.getChannel() == BaseRecognizer.HIDDEN) { continue; } System.out.println(smaliParser.tokenNames[token.getType()] + ": " + token.getText()); } } smaliParser parser = new smaliParser(tokens); parser.setVerboseErrors(verboseErrors); smaliParser.smali_file_return result = parser.smali_file(); if (parser.getNumberOfSyntaxErrors() > 0 || lexer.getNumberOfSyntaxErrors() > 0) { return false; } CommonTree t = (CommonTree) result.getTree(); CommonTreeNodeStream treeStream = new CommonTreeNodeStream(t); treeStream.setTokenStream(tokens); smaliTreeWalker dexGen = new smaliTreeWalker(treeStream); dexGen.dexFile = dexFile; dexGen.smali_file(); if (dexGen.getNumberOfSyntaxErrors() > 0) { return false; } return true; } }
zztobat-apktool
brut.apktool/apktool-lib/src/main/java/brut/androlib/mod/SmaliMod.java
Java
asf20
2,339
/** * Copyright 2011 Ryszard Wiśniewski <brut.alll@gmail.com> * * 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 brut.androlib.err; import brut.androlib.AndrolibException; /** * @author Ryszard Wiśniewski <brut.alll@gmail.com> */ public class OutDirExistsException extends AndrolibException { public OutDirExistsException(Throwable cause) { super(cause); } public OutDirExistsException(String message, Throwable cause) { super(message, cause); } public OutDirExistsException(String message) { super(message); } public OutDirExistsException() { } }
zztobat-apktool
brut.apktool/apktool-lib/src/main/java/brut/androlib/err/OutDirExistsException.java
Java
asf20
1,104
/** * Copyright 2011 Ryszard Wiśniewski <brut.alll@gmail.com> * * 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 brut.androlib.err; import brut.androlib.AndrolibException; /** * @author Ryszard Wiśniewski <brut.alll@gmail.com> */ public class InFileNotFoundException extends AndrolibException { public InFileNotFoundException(Throwable cause) { super(cause); } public InFileNotFoundException(String message, Throwable cause) { super(message, cause); } public InFileNotFoundException(String message) { super(message); } public InFileNotFoundException() { } }
zztobat-apktool
brut.apktool/apktool-lib/src/main/java/brut/androlib/err/InFileNotFoundException.java
Java
asf20
1,114
/** * Copyright 2011 Ryszard Wiśniewski <brut.alll@gmail.com> * * 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 brut.androlib.err; import brut.androlib.AndrolibException; /** * @author Ryszard Wiśniewski <brut.alll@gmail.com> */ public class CantFind9PatchChunk extends AndrolibException { public CantFind9PatchChunk(Throwable cause) { super(cause); } public CantFind9PatchChunk(String message, Throwable cause) { super(message, cause); } public CantFind9PatchChunk(String message) { super(message); } public CantFind9PatchChunk() { } }
zztobat-apktool
brut.apktool/apktool-lib/src/main/java/brut/androlib/err/CantFind9PatchChunk.java
Java
asf20
1,094