content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading.Tasks;
using CommunityToolkit.Common.Helpers;
using Windows.Storage;
namespace CommunityToolkit.WinUI.Helpers
{
/// <summary>
/// An extension of ApplicationDataStorageHelper with additional features for interop with the LocalCacheFolder.
/// </summary>
public partial class ApplicationDataStorageHelper
{
/// <summary>
/// Gets the local cache folder.
/// </summary>
public StorageFolder CacheFolder => AppData.LocalCacheFolder;
/// <summary>
/// Retrieves an object from a file in the LocalCacheFolder.
/// </summary>
/// <typeparam name="T">Type of object retrieved.</typeparam>
/// <param name="filePath">Path to the file that contains the object.</param>
/// <param name="default">Default value of the object.</param>
/// <returns>Waiting task until completion with the object in the file.</returns>
public Task<T> ReadCacheFileAsync<T>(string filePath, T @default = default)
{
return ReadFileAsync<T>(CacheFolder, filePath, @default);
}
/// <summary>
/// Retrieves the listings for a folder and the item types in the LocalCacheFolder.
/// </summary>
/// <param name="folderPath">The path to the target folder.</param>
/// <returns>A list of file types and names in the target folder.</returns>
public Task<IEnumerable<(DirectoryItemType ItemType, string Name)>> ReadCacheFolderAsync(string folderPath)
{
return ReadFolderAsync(CacheFolder, folderPath);
}
/// <summary>
/// Saves an object inside a file in the LocalCacheFolder.
/// </summary>
/// <typeparam name="T">Type of object saved.</typeparam>
/// <param name="filePath">Path to the file that will contain the object.</param>
/// <param name="value">Object to save.</param>
/// <returns>Waiting task until completion.</returns>
public Task CreateCacheFileAsync<T>(string filePath, T value)
{
return CreateFileAsync<T>(CacheFolder, filePath, value);
}
/// <summary>
/// Ensure a folder exists at the folder path specified in the LocalCacheFolder.
/// </summary>
/// <param name="folderPath">The path and name of the target folder.</param>
/// <returns>Waiting task until completion.</returns>
public Task CreateCacheFolderAsync(string folderPath)
{
return CreateFolderAsync(CacheFolder, folderPath);
}
/// <summary>
/// Deletes a file or folder item in the LocalCacheFolder.
/// </summary>
/// <param name="itemPath">The path to the item for deletion.</param>
/// <returns>Waiting task until completion.</returns>
public Task<bool> TryDeleteCacheItemAsync(string itemPath)
{
return TryDeleteItemAsync(CacheFolder, itemPath);
}
/// <summary>
/// Rename an item in the LocalCacheFolder.
/// </summary>
/// <param name="itemPath">The path to the target item.</param>
/// <param name="newName">The new nam for the target item.</param>
/// <returns>Waiting task until completion.</returns>
public Task<bool> TryRenameCacheItemAsync(string itemPath, string newName)
{
return TryRenameItemAsync(CacheFolder, itemPath, newName);
}
}
}
| 42.159091 | 116 | 0.635849 | [
"MIT"
] | w-ahmad/WindowsCommunityToolkit | CommunityToolkit.WinUI/Helpers/ObjectStorage/ApplicationDataStorageHelper.CacheFolder.cs | 3,710 | C# |
using System.Threading.Tasks;
using Hyperledger.Indy.PoolApi;
using Streetcred.Sdk.Contracts;
using Streetcred.Sdk.Utils;
namespace Streetcred.Sdk.Runtime
{
/// <inheritdoc />
public class DefaultPoolService : IPoolService
{
protected static Pool Pool;
/// <inheritdoc />
public virtual async Task<Pool> GetPoolAsync(string poolName, int protocolVersion)
{
if (Pool != null) return Pool;
await Pool.SetProtocolVersionAsync(protocolVersion);
return Pool = await Pool.OpenPoolLedgerAsync(poolName, null);
}
/// <inheritdoc />
public virtual async Task CreatePoolAsync(string poolName, string genesisFile, int protocolVersion)
{
await Pool.SetProtocolVersionAsync(protocolVersion);
var poolConfig = new {genesis_txn = genesisFile}.ToJson();
await Pool.CreatePoolLedgerConfigAsync(poolName, poolConfig);
}
}
} | 30.375 | 107 | 0.661523 | [
"Apache-2.0"
] | dznz/streetcred-sdk | src/Streetcred.Sdk/Runtime/DefaultPoolService.cs | 974 | C# |
using System;
namespace DlibDotNet.Dnn
{
public sealed class Adam : Solver
{
#region Constructors
public Adam()
: this(0.0005f, 0.9f, 0.999f)
{
}
public Adam(float weightDecay, float momentum1, float momentum2)
{
this.NativePtr = NativeMethods.adam_new(weightDecay, momentum1, momentum2);
}
#endregion
#region Properties
public override int SolverType
{
get
{
return (int)NativeMethods.OptimizerType.Adam;
}
}
#endregion
#region Methods
#region Overrids
/// <summary>
/// Releases all unmanaged resources.
/// </summary>
protected override void DisposeUnmanaged()
{
base.DisposeUnmanaged();
if (this.NativePtr == IntPtr.Zero)
return;
NativeMethods.adam_delete(this.NativePtr);
}
#endregion
#endregion
}
} | 19.034483 | 88 | 0.488225 | [
"MIT"
] | thanhthai18/DlibDotNet | src/DlibDotNet/Dnn/Adam.cs | 1,106 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MultiSelectionCalendar;
using Reunion.Common;
using Reunion.Common.Model;
using Reunion.Web.Models;
using TUtils.Common.MVC;
namespace Reunion.Web.Controllers
{
public class ParticipantController : Controller
{
private readonly IReunionBL _bl;
private readonly IIdentityManager _identityManager;
public ParticipantController(
IReunionBL bl,
IIdentityManager identityManager)
{
_bl = bl;
_identityManager = identityManager;
}
public ActionResult AcceptFinalDate(string id)
{
var unguessableParticipantId = id;
var participant = _bl.GetVerifiedParticipant(unguessableParticipantId);
if (participant == null)
return RedirectToAction("Index", "Home");
_bl.AcceptFinalDate(participantId:participant.Id,reunionId:participant.Reunion.Id);
return RedirectToAction(actionName: nameof(Edit), routeValues: new { id = unguessableParticipantId });
}
public ActionResult RejectFinalDateOnly(string id)
{
var unguessableParticipantId = id;
var participant = _bl.GetVerifiedParticipant(unguessableParticipantId);
if (participant == null)
return RedirectToAction("Index", "Home");
_bl.RejectFinalDateOnly(participantId: participant.Id, reunionId: participant.Reunion.Id);
return RedirectToAction(actionName: nameof(Edit), routeValues: new { id = unguessableParticipantId });
}
public ActionResult RejectCompletely(string id)
{
var unguessableParticipantId = id;
var participant = _bl.GetVerifiedParticipant(unguessableParticipantId);
if (participant == null)
return RedirectToAction("Index", "Home");
_bl.RejectCompletely(participantId: participant.Id, reunionId: participant.Reunion.Id);
return RedirectToAction("Index","Home");
}
// GET: Participant
[HttpGet]
public ActionResult Edit(string id)
{
var unguessableParticipantId = id;
var participant = _bl.GetVerifiedParticipant(unguessableParticipantId);
if ( participant == null )
return RedirectToAction("Index", "Home");
DateTime? finalInvitationdate;
bool? hasAcceptedFinalInvitationdate;
IEnumerable<DateTime> daysToBeChecked;
var preferredDates = _bl.GetTimeRangesOfParticipant(
reunionId: participant.Reunion.Id,
participantId:participant.Id,
finalInvitationdate: out finalInvitationdate,
hasAcceptedFinalInvitationdate: out hasAcceptedFinalInvitationdate,
daysToBeChecked: out daysToBeChecked);
ViewBag.ShowLanguageSwitch = false;
ViewBag.LanguageIsoCode = participant.LanguageIsoCodeOfPlayer;
return View("ShowMyCalendar", new ParticipantFeedbackViewModel(
participant,
preferredDates: preferredDates,
timeRangesOfOrganizer: _bl.GetTimeRangesOfReunion(participant.Reunion.Id),
finalInvitationDate:finalInvitationdate,
hasAcceptedFinalInvitationdate:hasAcceptedFinalInvitationdate,
daysToBeChecked: daysToBeChecked));
}
/// <summary>
/// saves updates to the preferences of a participant
/// </summary>
/// <param name="model">
/// all ignored except properties
/// - PossibleDates
/// - UnguessableParticipantId
/// </param>
/// <returns></returns>
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ParticipantFeedbackViewModel model)
{
var unguessableParticipantId = model.UnguessableParticipantId;
var preferredTimeRanges = model.PossibleDates
.GetDateRangesFromString()
.Where(r=>r.SelectionIdx!=0)
.Select(r => new TimeRange(
start: r.Start,
end: r.End,
preference: (PreferenceEnum) r.SelectionIdx,
player: null,
reunion: null))
.ToList();
_bl.UpdateTimeRangesOfParticipant(preferredTimeRanges, unguessableIdOfParticipant:unguessableParticipantId);
return RedirectToAction(actionName:nameof(Edit),routeValues:new {id= unguessableParticipantId});
}
}
} | 33.5 | 111 | 0.752593 | [
"MIT"
] | Tommmi/Reunion | source/Reunion.Web/Controllers/ParticipantController.cs | 3,955 | C# |
using System.IO;
using System.Net;
using System.Text;
using Xunit;
namespace RequestReduce.Facts.Integration
{
public class SassLessCoffeeFacts
{
[Fact]
public void WillGetCompilesLessAsCss()
{
const string expected = "#header {\n color: #4d926f;\n}\n";
string result;
var client = WebRequest.Create("http://localhost:8877/styles/Style.less");
var httpResponse = client.GetResponse();
using (var streameader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
{
result = streameader.ReadToEnd();
}
Assert.Equal(expected, result);
Assert.Contains("text/css", httpResponse.ContentType);
}
[Fact]
public void WillGetCompilesLessAsCssWithParameters()
{
const string expected = "#header {\n color: #4d926f;\n}\n";
string result;
var client = WebRequest.Create("http://localhost:8877/styles/Parameters.less?brand_color=%234d926f");
var httpResponse = client.GetResponse();
using (var streameader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
{
result = streameader.ReadToEnd();
}
Assert.Equal(expected, result);
Assert.Contains("text/css", httpResponse.ContentType);
}
[Fact]
public void WillGetCompilesSassAsCss()
{
const string expected = ".content-navigation {\n border-color: #3bbfce;\n color: #2ca2af; }\n\r\n";
string result;
var client = WebRequest.Create("http://localhost:8877/styles/test.sass");
var httpResponse = client.GetResponse();
using (var streameader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
{
result = streameader.ReadToEnd();
}
Assert.Equal(expected, result);
Assert.Contains("text/css", httpResponse.ContentType);
}
[Fact]
public void WillGetCompilesCoffeeAsJs()
{
const string expected = "(function() {\n var square;\n\n square = function(x) {\n return x * x;\n };\n\n}).call(this);\n\r\n";
string result;
var client = WebRequest.Create("http://localhost:8877/scripts/test.coffee");
var httpResponse = client.GetResponse();
using (var streameader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
{
result = streameader.ReadToEnd();
}
Assert.Equal(expected, result);
Assert.Contains("text/javascript", httpResponse.ContentType);
}
}
}
| 35.975 | 145 | 0.565323 | [
"Apache-2.0"
] | andrewdavey/RequestReduce | RequestReduce.Facts.Integration/SassLessCoffeeFacts.cs | 2,880 | C# |
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using SpaceShared;
using StardewModdingAPI;
using StardewValley;
namespace SpaceCore.Framework
{
internal static class Commands
{
internal static void Register()
{
Command.Register("player_giveexp", Commands.ExpCommand);
Command.Register("asset_invalidate", Commands.InvalidateCommand);
Command.Register("exttilesheets_dump", Commands.DumpTilesheetsCommand);
Command.Register("dump_spacecore_skills", Commands.DumpSkills);
//Command.register( "test", ( args ) => Game1.player.addItemByMenuIfNecessary( new TestObject() ) );
//SpaceCore.modTypes.Add( typeof( TestObject ) );
}
/// <summary>Show a report of currently registered skills and professions.</summary>
/// <param name="args">The command arguments.</param>
private static void DumpSkills(string[] args)
{
StringBuilder report = new StringBuilder();
if (Skills.SkillsByName.Any())
{
report.AppendLine("The following custom skills are registered with SpaceCore.");
report.AppendLine();
foreach (Skills.Skill skill in Skills.SkillsByName.Values)
{
// base skill info
report.AppendLine(skill.Id);
report.AppendLine("--------------------------------------------------");
if (Context.IsWorldReady)
{
report.AppendLine($"Level: {Skills.GetSkillLevel(Game1.player, skill.Id)}");
report.AppendLine($"Experience: {Skills.GetExperienceFor(Game1.player, skill.Id)}");
}
// level perks
{
var perks = Enumerable.Range(1, 10)
.Select(level => new { level, perks = skill.GetExtraLevelUpInfo(level) })
.Where(p => p.perks.Any())
.ToArray();
if (perks.Any())
{
report.AppendLine();
report.AppendLine("Level perks:");
foreach (var entry in perks)
report.AppendLine($" - level {entry.level}: {string.Join(", ", entry.perks)}");
}
}
// professions
if (skill.Professions.Any())
{
report.AppendLine();
report.AppendLine("Professions:");
foreach (var profession in skill.Professions)
{
int vanillaId = profession.GetVanillaId();
bool hasProfession = Context.IsWorldReady && Game1.player.professions.Contains(vanillaId);
report.AppendLine($" [{(hasProfession ? "X" : " ")}] {profession.GetName()}");
report.AppendLine($" - ID: {profession.Id} ({vanillaId})");
report.AppendLine($" - Description: {profession.GetDescription()}");
report.AppendLine();
}
}
else
report.AppendLine();
report.AppendLine();
}
}
else
report.AppendLine("There are no custom skills registered with SpaceCore currently.");
Log.Info(report.ToString());
}
private static void ExpCommand(string[] args)
{
if (args.Length != 2)
{
Log.Info("Usage: player_giveexp <skill> <amt>");
}
string skillName = args[0].ToLower();
int amt = int.Parse(args[1]);
if (skillName == "farming") Game1.player.gainExperience(Farmer.farmingSkill, amt);
else if (skillName == "foraging") Game1.player.gainExperience(Farmer.foragingSkill, amt);
else if (skillName == "mining") Game1.player.gainExperience(Farmer.miningSkill, amt);
else if (skillName == "fishing") Game1.player.gainExperience(Farmer.fishingSkill, amt);
else if (skillName == "combat") Game1.player.gainExperience(Farmer.combatSkill, amt);
else if (skillName == "luck") Game1.player.gainExperience(Farmer.luckSkill, amt);
else
{
var skill = Skills.GetSkill(skillName);
if (skill == null)
{
Log.Info("No such skill exists");
}
else
{
Game1.player.AddCustomSkillExperience(skill, amt);
}
}
}
private static void InvalidateCommand(string[] args)
{
if (args.Length == 0)
{
Log.Info("Usage: asset_invalidate <asset1> [asset2] [...]");
}
foreach (string arg in args)
{
SpaceCore.Instance.Helper.Content.InvalidateCache(arg);
}
}
private static void DumpTilesheetsCommand(string[] args)
{
foreach (var asset in TileSheetExtensions.ExtendedTextureAssets)
{
Log.Info($"Dumping for asset {asset.Key} (has {asset.Value.Extensions.Count} extensions)");
Stream stream = File.OpenWrite(Path.GetFileNameWithoutExtension(asset.Key) + "-0.png");
var tex = Game1.content.Load<Texture2D>(asset.Key);
tex.SaveAsPng(stream, tex.Width, tex.Height);
stream.Close();
for (int i = 0; i < asset.Value.Extensions.Count; ++i)
{
Log.Info("\tDumping extended " + (i + 1));
stream = File.OpenWrite(Path.GetFileNameWithoutExtension(asset.Key) + $"-{i + 1}.png");
tex = asset.Value.Extensions[i];
tex.SaveAsPng(stream, tex.Width, tex.Height);
stream.Close();
}
}
}
}
}
| 41.025806 | 118 | 0.493159 | [
"MIT"
] | ChulkyBow/StardewValleyMods | SpaceCore/Framework/Commands.cs | 6,359 | C# |
using System.Collections.Generic;
using Orchard.Mvc.Routes;
using Orchard.WebApi.Routes;
namespace Meso.TyMetro.Routing
{
public class RoleApiRoutes : IHttpRouteProvider
{
public IEnumerable<Orchard.Mvc.Routes.RouteDescriptor> GetRoutes()
{
return new[]{
new HttpRouteDescriptor {
Name = "TyMetroRoleApiRoute",
Priority = 20,
RouteTemplate = "api/roles/{action}",
Defaults = new { area = "Meso.TyMetro", controller = "RoleApi"}
}
};
}
public void GetRoutes(ICollection<Orchard.Mvc.Routes.RouteDescriptor> routes)
{
foreach (RouteDescriptor routeDescriptor in GetRoutes())
{
routes.Add(routeDescriptor);
}
}
}
} | 27.482759 | 85 | 0.593476 | [
"BSD-3-Clause"
] | pochuan0720/OrchardMeso1.10.2 | src/Orchard.Web/Modules/Meso.TyMetro/Routing/RoleApiRoutes.cs | 799 | C# |
using System;
using System.Collections.Generic;
using StandWorld.Definitions;
using StandWorld.Helpers;
using StandWorld.Visuals;
using UnityEngine;
namespace StandWorld.Entities
{
public class Mountain : Tilable
{
private ConnectedTilable _connectedTilable;
public Mountain(Vector2Int position, TilableDef tilableDef)
{
this.position = position;
this.tilableDef = tilableDef;
mainGraphic = GraphicInstance.GetNew(
this.tilableDef.graphics,
default(Color),
Res.textures[this.tilableDef.graphics.textureName + "_0"],
1
);
_connectedTilable = new ConnectedTilable(this);
addGraphics = new Dictionary<string, GraphicInstance>();
}
public override void UpdateGraphics()
{
_connectedTilable.UpdateGraphics();
}
}
}
| 26.777778 | 74 | 0.59751 | [
"MIT"
] | Stand1k/StandWorld | Assets/StandWorld/Scripts/Entities/Mountain.cs | 966 | C# |
namespace RTCV.Plugins
{
using System;
using System.ComponentModel.Composition;
using RTCV.PluginHost;
[Export(typeof(IPlugin))]
public class TestPlugin : IPlugin
{
public string Name => "TestPlugin";
public string Description => "Test plugin";
public string Author => "Narry";
#pragma warning disable SA1001 //Avoiding spaces between commas makes version string more clear
public Version Version => new Version(0,0,1);
public RTCSide SupportedSide => RTCSide.Both;
public bool Start(RTCSide side)
{
Console.WriteLine("Test plugin loaded!");
return true;
}
public bool Stop()
{
return true;
}
public void Dispose()
{
}
}
}
| 23.882353 | 103 | 0.583744 | [
"MIT"
] | fossabot/RTCV | Source/Plugins/TestPlugin/TestPlugin.cs | 812 | C# |
namespace P08.MilitaryElite.Models
{
using Contracts;
public class Repair : IRepair
{
public string PartName { get; private set; }
public int HoursWorked { get; private set; }
public Repair(string partName, int hoursWorked)
{
this.PartName = partName;
this.HoursWorked = hoursWorked;
}
public override string ToString()
{
return $"Part Name: {this.PartName} Hours Worked: {this.HoursWorked}";
}
}
}
| 22.608696 | 82 | 0.578846 | [
"MIT"
] | msotiroff/Softuni-learning | C# Fundamentals Module/CSharp-OOP-Basics/Feb 2018 instance/05.InterfacesAndAbstraction/InterfacesAndAbstraction/P08.MilitaryElite/Models/Repair.cs | 522 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.KubernetesConfiguration.Inputs
{
/// <summary>
/// Specifies that the scope of the extensionInstance is Namespace
/// </summary>
public sealed class ScopeNamespaceArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Namespace where the extensionInstance will be created for an Namespace scoped extensionInstance. If this namespace does not exist, it will be created
/// </summary>
[Input("targetNamespace")]
public Input<string>? TargetNamespace { get; set; }
public ScopeNamespaceArgs()
{
}
}
}
| 31.344828 | 162 | 0.685369 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/KubernetesConfiguration/Inputs/ScopeNamespaceArgs.cs | 909 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityModel;
using IdentityServer.Data.Entities;
using IdentityServer4.Events;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace IdentityServerHost.Quickstart.UI
{
/// <summary>
/// This sample controller implements a typical login/logout/provision workflow for local and external accounts.
/// The login service encapsulates the interactions with the user data store. This data store is in-memory only and cannot be used for production!
/// The interaction service provides a way for the UI to communicate with identityserver for validation and context retrieval
/// </summary>
[SecurityHeaders]
[AllowAnonymous]
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IIdentityServerInteractionService _interaction;
private readonly IClientStore _clientStore;
private readonly IAuthenticationSchemeProvider _schemeProvider;
private readonly IEventService _events;
public AccountController(
IIdentityServerInteractionService interaction,
IClientStore clientStore,
IAuthenticationSchemeProvider schemeProvider,
IEventService events,
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager)
{
// if the TestUserStore is not in DI, then we'll just use the global users collection
// this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity)
_interaction = interaction;
_clientStore = clientStore;
_schemeProvider = schemeProvider;
_events = events;
_userManager = userManager;
_signInManager = signInManager;
}
/// <summary>
/// Entry point into the login workflow
/// </summary>
[HttpGet]
public async Task<IActionResult> Login(string returnUrl)
{
// build a model so we know what to show on the login page
var vm = await BuildLoginViewModelAsync(returnUrl);
if (vm.IsExternalLoginOnly)
{
// we only have one option for logging in and it's an external provider
return RedirectToAction("Challenge", "External", new { scheme = vm.ExternalLoginScheme, returnUrl });
}
return View(vm);
}
/// <summary>
/// Handle postback from username/password login
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginInputModel model, string button)
{
// check if we are in the context of an authorization request
var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);
// the user clicked the "cancel" button
if (button != "login")
{
if (context != null)
{
// if the user cancels, send a result back into IdentityServer as if they
// denied the consent (even if this client does not require consent).
// this will send back an access denied OIDC error response to the client.
await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied);
// we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
if (context.IsNativeClient())
{
// The client is native, so this change in how to
// return the response is for better UX for the end user.
return this.LoadingPage("Redirect", model.ReturnUrl);
}
return Redirect(model.ReturnUrl);
}
else
{
// since we don't have a valid context, then we just go back to the home page
return Redirect("~/");
}
}
if (ModelState.IsValid)
{
// validate username/password against in-memory store
var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberLogin, lockoutOnFailure: true);
if (result.Succeeded)
{
var user = await _userManager.FindByNameAsync(model.Username);
await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName, clientId: context?.Client?.ClientId));
// only set explicit expiration here if user chooses "remember me".
// otherwise we rely upon expiration configured in cookie middleware.
AuthenticationProperties props = null;
if (AccountOptions.AllowRememberLogin && model.RememberLogin)
{
props = new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
};
};
if (context != null)
{
if (context.IsNativeClient())
{
// The client is native, so this change in how to
// return the response is for better UX for the end user.
return this.LoadingPage("Redirect", model.ReturnUrl);
}
// we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
return Redirect(model.ReturnUrl);
}
// request for a local page
if (Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
else if (string.IsNullOrEmpty(model.ReturnUrl))
{
return Redirect("~/");
}
else
{
// user might have clicked on a malicious link - should be logged
throw new Exception("invalid return URL");
}
}
await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials", clientId: context?.Client.ClientId));
ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
}
// something went wrong, show form with error
var vm = await BuildLoginViewModelAsync(model);
return View(vm);
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(error.Code, error.Description);
}
}
/// <summary>
/// Show logout page
/// </summary>
[HttpGet]
public async Task<IActionResult> Logout(string logoutId)
{
// build a model so the logout page knows what to display
var vm = await BuildLogoutViewModelAsync(logoutId);
if (vm.ShowLogoutPrompt == false)
{
// if the request for logout was properly authenticated from IdentityServer, then
// we don't need to show the prompt and can just log the user out directly.
return await Logout(vm);
}
return View(vm);
}
/// <summary>
/// Handle logout page postback
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout(LogoutInputModel model)
{
// build a model so the logged out page knows what to display
var vm = await BuildLoggedOutViewModelAsync(model.LogoutId);
if (User?.Identity.IsAuthenticated == true)
{
// delete local authentication cookie
await HttpContext.SignOutAsync();
// raise the logout event
await _events.RaiseAsync(new UserLogoutSuccessEvent(User.GetSubjectId(), User.GetDisplayName()));
}
// check if we need to trigger sign-out at an upstream identity provider
if (vm.TriggerExternalSignout)
{
// build a return URL so the upstream provider will redirect back
// to us after the user has logged out. this allows us to then
// complete our single sign-out processing.
string url = Url.Action("Logout", new { logoutId = vm.LogoutId });
// this triggers a redirect to the external provider for sign-out
return SignOut(new AuthenticationProperties { RedirectUri = url }, vm.ExternalAuthenticationScheme);
}
return View("LoggedOut", vm);
}
[HttpGet]
public IActionResult AccessDenied()
{
return View();
}
/*****************************************/
/* helper APIs for the AccountController */
/*****************************************/
private async Task<LoginViewModel> BuildLoginViewModelAsync(string returnUrl)
{
var context = await _interaction.GetAuthorizationContextAsync(returnUrl);
if (context?.IdP != null && await _schemeProvider.GetSchemeAsync(context.IdP) != null)
{
var local = context.IdP == IdentityServer4.IdentityServerConstants.LocalIdentityProvider;
// this is meant to short circuit the UI and only trigger the one external IdP
var vm = new LoginViewModel
{
EnableLocalLogin = local,
ReturnUrl = returnUrl,
Username = context?.LoginHint,
};
if (!local)
{
vm.ExternalProviders = new[] { new ExternalProvider { AuthenticationScheme = context.IdP } };
}
return vm;
}
var schemes = await _schemeProvider.GetAllSchemesAsync();
var providers = schemes
.Where(x => x.DisplayName != null)
.Select(x => new ExternalProvider
{
DisplayName = x.DisplayName ?? x.Name,
AuthenticationScheme = x.Name
}).ToList();
var allowLocal = true;
if (context?.Client.ClientId != null)
{
var client = await _clientStore.FindEnabledClientByIdAsync(context.Client.ClientId);
if (client != null)
{
allowLocal = client.EnableLocalLogin;
if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
{
providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList();
}
}
}
return new LoginViewModel
{
AllowRememberLogin = AccountOptions.AllowRememberLogin,
EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin,
ReturnUrl = returnUrl,
Username = context?.LoginHint,
ExternalProviders = providers.ToArray()
};
}
private async Task<LoginViewModel> BuildLoginViewModelAsync(LoginInputModel model)
{
var vm = await BuildLoginViewModelAsync(model.ReturnUrl);
vm.Username = model.Username;
vm.RememberLogin = model.RememberLogin;
return vm;
}
private async Task<LogoutViewModel> BuildLogoutViewModelAsync(string logoutId)
{
var vm = new LogoutViewModel { LogoutId = logoutId, ShowLogoutPrompt = AccountOptions.ShowLogoutPrompt };
if (User?.Identity.IsAuthenticated != true)
{
// if the user is not authenticated, then just show logged out page
vm.ShowLogoutPrompt = false;
return vm;
}
var context = await _interaction.GetLogoutContextAsync(logoutId);
if (context?.ShowSignoutPrompt == false)
{
// it's safe to automatically sign-out
vm.ShowLogoutPrompt = false;
return vm;
}
// show the logout prompt. this prevents attacks where the user
// is automatically signed out by another malicious web page.
return vm;
}
private async Task<LoggedOutViewModel> BuildLoggedOutViewModelAsync(string logoutId)
{
// get context information (client name, post logout redirect URI and iframe for federated signout)
var logout = await _interaction.GetLogoutContextAsync(logoutId);
var vm = new LoggedOutViewModel
{
AutomaticRedirectAfterSignOut = AccountOptions.AutomaticRedirectAfterSignOut,
PostLogoutRedirectUri = logout?.PostLogoutRedirectUri,
ClientName = string.IsNullOrEmpty(logout?.ClientName) ? logout?.ClientId : logout?.ClientName,
SignOutIframeUrl = logout?.SignOutIFrameUrl,
LogoutId = logoutId
};
if (User?.Identity.IsAuthenticated == true)
{
var idp = User.FindFirst(JwtClaimTypes.IdentityProvider)?.Value;
if (idp != null && idp != IdentityServer4.IdentityServerConstants.LocalIdentityProvider)
{
var providerSupportsSignout = await HttpContext.GetSchemeSupportsSignOutAsync(idp);
if (providerSupportsSignout)
{
if (vm.LogoutId == null)
{
// if there's no current logout context, we need to create one
// this captures necessary info from the current logged in user
// before we signout and redirect away to the external IdP for signout
vm.LogoutId = await _interaction.CreateLogoutContextAsync();
}
vm.ExternalAuthenticationScheme = idp;
}
}
}
return vm;
}
}
}
| 41.263298 | 150 | 0.563906 | [
"MIT"
] | dodandeniya/MyAppointments | myAppointments-service/IdentityServer/Quickstart/Account/AccountController.cs | 15,515 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using YTLiveLib.Classes.API;
namespace YTLiveLib.Events {
public class ReceiveMessageArgs : EventArgs {
public ChatMessage ChatMessage;
public ReceiveMessageArgs(ChatMessage message) {
ChatMessage = message;
}
}
}
| 21.866667 | 56 | 0.698171 | [
"MIT"
] | jpdante/YTLiveLib | YTLiveLib/Events/ReceiveMessageArgs.cs | 330 | C# |
namespace ScalaWay.Domain.Abstractions.Auditing
{
public interface IHasCreationTime
{
DateTime CreateTime { get; set; }
}
public interface IHasCreationTime<TIdentityKey> : IHasCreationTime
{
TIdentityKey CreatorId { get; set; }
}
} | 22.75 | 70 | 0.673993 | [
"MIT"
] | ScalaWay/ScalaWay | src/ScalaWay.Domain.Abstractions/Auditing/IHasCreationTime.cs | 275 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.ComponentModel.DataAnnotations;
using Squidex.Shared;
using Squidex.Web;
namespace Squidex.Areas.Api.Controllers.Apps.Models
{
public sealed class ContributorDto : Resource
{
/// <summary>
/// The id of the user that contributes to the app.
/// </summary>
[Required]
public string ContributorId { get; set; }
/// <summary>
/// The role of the contributor.
/// </summary>
public string Role { get; set; }
public static ContributorDto FromIdAndRole(string id, string role, ApiController controller, string app)
{
var result = new ContributorDto { ContributorId = id, Role = role };
return result.CreateLinks(controller, app);
}
private ContributorDto CreateLinks(ApiController controller, string app)
{
if (!controller.IsUser(ContributorId))
{
if (controller.HasPermission(Permissions.AppContributorsAssign, app))
{
AddPostLink("update", controller.Url<AppContributorsController>(x => nameof(x.PostContributor), new { app }));
}
if (controller.HasPermission(Permissions.AppContributorsRevoke, app))
{
AddDeleteLink("delete", controller.Url<AppContributorsController>(x => nameof(x.DeleteContributor), new { app, id = ContributorId }));
}
}
return this;
}
}
}
| 35.566038 | 154 | 0.525199 | [
"MIT"
] | mgnz/squidex | src/Squidex/Areas/Api/Controllers/Apps/Models/ContributorDto.cs | 1,888 | C# |
// DbgDraw for Unity. Copyright (c) 2019 Peter Schraut (www.console-dev.de). See LICENSE.md
// https://github.com/pschraut/UnityDbgDraw
using UnityEngine;
#pragma warning disable IDE0018 // Variable declaration can be inlined
#pragma warning disable IDE0017 // Object initialization can be simplified
namespace Oddworm.Framework
{
public partial class DbgDraw
{
/// <summary>
/// Draws a line from start to end.
/// </summary>
[System.Diagnostics.Conditional("UNITY_EDITOR")]
[System.Diagnostics.Conditional("DEVELOPMENT_BUILD")]
public static void Line(Vector3 start, Vector3 end, Color color, float duration = 0, bool depthTest = true)
{
LineBatchJob job;
if (!TryGetLineBatch(out job, depthTest, UnityEngine.Rendering.CullMode.Off))
return;
job.AddLine(start, end, color, duration);
}
}
}
| 35.5 | 115 | 0.659805 | [
"MIT"
] | pschraut/UnityDbgDraw | Runtime/Core/DbgDraw.Line.cs | 925 | C# |
using Blogifier.Core.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace App
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddBlogDatabase(Configuration);
services.AddBlogSecurity();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}
}
}
| 25.644444 | 79 | 0.594454 | [
"MIT"
] | jwmxyz/Blogifier.Core | src/App/Startup.cs | 1,154 | C# |
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
namespace MoneroInteractive.WebApp.Localization
{
public class LocalizationConfiguration
{
public string[] AvailableLanguages { get; set; }
public string DefaultLanguage { get; set; } = "en";
}
}
| 23.75 | 59 | 0.734211 | [
"MIT"
] | leonardochaia/xmr-tutorials | MoneroInteractive.WebApp/Localization/LocalizationConfiguration.cs | 382 | C# |
using System;
using System.Collections.Generic;
using ParadoxNotion;
using ParadoxNotion.Serialization.FullSerializer;
namespace ParadoxNotion.Serialization
{
///Handles UnityObject references serialization
public class fsUnityObjectConverter : fsConverter
{
public override bool CanProcess(Type type) {
return typeof(UnityEngine.Object).RTIsAssignableFrom(type);
}
public override bool RequestCycleSupport(Type storageType) {
return false;
}
public override bool RequestInheritanceSupport(Type storageType) {
return false;
}
public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) {
var database = Serializer.ReferencesDatabase;
if ( database == null ) {
serialized = null;
return fsResult.Warn("No database references provided for serialization");
}
var o = instance as UnityEngine.Object;
//for null store 0
if ( ReferenceEquals(o, null) ) {
serialized = new fsData(0);
return fsResult.Success;
}
//this is done to avoid serializing 0 because it's default value of int and will not be printed,
//which is done for performance. Thus we always start from index 1. 0 is always null.
if ( database.Count == 0 ) {
database.Add(null);
}
//search reference match
var index = -1;
for ( var i = 0; i < database.Count; i++ ) {
if ( ReferenceEquals(database[i], o) ) {
index = i;
break;
}
}
//if no match, add new
if ( index <= 0 ) {
index = database.Count;
database.Add(o);
}
serialized = new fsData(index);
return fsResult.Success;
}
public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) {
var database = Serializer.ReferencesDatabase;
if ( database == null ) {
return fsResult.Warn("A Unity Object reference has not been deserialized because no database references was provided.");
}
var index = (int)data.AsInt64;
if ( index >= database.Count ) {
return fsResult.Warn("A Unity Object reference has not been deserialized because no database entry was found in provided database references.");
}
var reference = database[index];
if ( ReferenceEquals(reference as UnityEngine.Object, null) || storageType.RTIsAssignableFrom(reference.GetType()) ) {
instance = reference;
}
return fsResult.Success;
}
public override object CreateInstance(fsData data, Type storageType) {
return null;
}
}
} | 33.296703 | 160 | 0.572937 | [
"MIT"
] | Marcgs96/Guild-Master | Guild Master/Assets/ParadoxNotion/CanvasCore/Common/Runtime/Serialization/fsUnityObjectConverter.cs | 3,032 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Storage")]
[assembly: AssemblyDescription("This plugin acquires Storage data. Values come from the Linux System.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MISD OWL Team")]
[assembly: AssemblyProduct("MISD OWL")]
[assembly: AssemblyCopyright("Copyright © 2012 Paul Brombosch, Ehssan Doust, David Krauss, Fabian Müller, Yannic Noller, Hanna Schäfer, Jonas Scheurich, Arno Schneider, Sebastian Zillessen")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| 43.607143 | 191 | 0.757576 | [
"BSD-3-Clause"
] | sebastianzillessen/MISD-OWL | Code/MISDCode/MISD.Plugins.Linux/Storage/AssemblyInfo.cs | 1,224 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO.Abstractions.TestingHelpers;
using System.Collections.Generic;
using Cmf.Common.Cli.Objects;
using Cmf.Common.Cli.Commands;
using Cmf.Common.Cli.Handlers;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.IO.Abstractions;
using System.CommandLine.IO;
using tests.Objects;
namespace tests.Specs
{
[TestClass]
public class JsonValidator
{
[TestMethod]
public void Data_JsonValidator_HappyPath()
{
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
{
{ "/test/cmfpackage.json", new MockFileData(
@"{
""packageId"": ""Cmf.Custom.Package"",
""version"": ""1.1.0"",
""description"": ""This package deploys Critical Manufacturing Customization"",
""packageType"": ""Root"",
""isInstallable"": true,
""isUniqueInstall"": false,
""dependencies"": [
{
""id"": ""Cmf.Custom.Data"",
""version"": ""1.1.0""
},
{
""id"": ""Cmf.Custom.IoT"",
""version"": ""1.1.0""
}
]
}")
},
{ "/test/Data/cmfpackage.json", new CmfMockJsonData(
@"{
""packageId"": ""Cmf.Custom.Data"",
""version"": ""1.1.0"",
""description"": ""Cmf Custom Data Package"",
""packageType"": ""Data"",
""isInstallable"": true,
""isUniqueInstall"": true,
""contentToPack"": [
{
""source"": ""MasterData/$(version)/*"",
""target"": ""MasterData/$(version)/"",
""contentType"": ""MasterData""
}
]
}")
},
{ "/test/Data/MasterData/1.1.0/Test.json", new CmfMockJsonData(
@"{
""<SM>Config"": {
""1"": {
""ParentPath"": ""/SMT/BlockCheckListOnFalseParameters/"",
""Name"": ""IsEnabled"",
""Value"": ""Yes"",
""ValueType"": ""String""
}
}
}")
}
});
BuildCommand buildCommand = new BuildCommand(fileSystem.FileSystem);
var cmd = new Command("build");
buildCommand.Configure(cmd);
var console = new TestConsole();
cmd.Invoke(new string[] {
"test/Data/"
}, console);
Assert.IsTrue(console.Error == null || string.IsNullOrEmpty(console.Error.ToString()), $"Json Validator failed {console.Error.ToString()}");
}
[TestMethod]
public void Data_JsonValidator_FailData()
{
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
{
{ "/test/cmfpackage.json", new CmfMockJsonData(
@"{
""packageId"": ""Cmf.Custom.Package"",
""version"": ""1.1.0"",
""description"": ""This package deploys Critical Manufacturing Customization"",
""packageType"": ""Root"",
""isInstallable"": true,
""isUniqueInstall"": false,
""dependencies"": [
{
""id"": ""Cmf.Custom.Data"",
""version"": ""1.1.0""
},
{
""id"": ""Cmf.Custom.IoT"",
""version"": ""1.1.0""
}
]
}")
},
{ "/test/Data/cmfpackage.json", new CmfMockJsonData(
@"{
""packageId"": ""Cmf.Custom.Data"",
""version"": ""1.1.0"",
""description"": ""Cmf Custom Data Package"",
""packageType"": ""Data"",
""isInstallable"": true,
""isUniqueInstall"": false,
""contentToPack"": [
{
{
""source"": ""MasterData/$(version)/*"",
""target"": ""MasterData /$(version)/"",
""contentType"": ""MasterData""
},
]
}")
},
{ "/test/Data/MasterData/1.1.0/Test.json", new CmfMockJsonData(
@"{
""<SM>Config"": {
""1"": {
""ParentPath"": ""/SMT/BlockCheckListOnFalseParameters/"",
""Name"": ""IsEnabled"",
""Value"": ""Yes"",
""ValueType"": ""String""
}")
}
});
BuildCommand buildCommand = new BuildCommand(fileSystem.FileSystem);
var cmd = new Command("build");
buildCommand.Configure(cmd);
var console = new TestConsole();
cmd.Invoke(new string[] {
"test/Data/"
}, console);
Assert.IsTrue(console.Error != null && !string.IsNullOrEmpty(console.Error.ToString()), $"Json Validator failed for Data Package: {console.Error.ToString()}");
}
[TestMethod]
public void IoTData_JsonValidator_FailData()
{
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
{
{ "/test/cmfpackage.json", new CmfMockJsonData(
@"{
""packageId"": ""Cmf.Custom.Package"",
""version"": ""1.1.0"",
""description"": ""This package deploys Critical Manufacturing Customization"",
""packageType"": ""Root"",
""isInstallable"": true,
""isUniqueInstall"": false,
""dependencies"": [
{
""id"": ""Cmf.Custom.Data"",
""version"": ""1.1.0""
},
{
""id"": ""Cmf.Custom.IoT"",
""version"": ""1.1.0""
}
]
}")
},
{ "/test/IoT/cmfpackage.json", new CmfMockJsonData(
@"{
""packageId"": ""Cmf.Custom.IoT"",
""version"": ""1.1.0"",
""description"": ""Cmf Custom Foxconn IoT Package"",
""packageType"": ""Root"",
""isInstallable"": true,
""isUniqueInstall"": false,
""dependencies"": [
{
""id"": ""Cmf.Custom.IoTData"",
""version"": ""1.1.0""
}
]
}")
},
{ "/test/IoTData/cmfpackage.json", new CmfMockJsonData(
@"{
""packageId"": ""Cmf.Custom.IoTData"",
""version"": ""1.1.0"",
""description"": ""Cmf Custom Foxconn IoTData Package"",
""packageType"": ""IoTData"",
""isInstallable"": true,
""isUniqueInstall"": false,
""contentToPack"": [
{
{
""source"": ""MasterData/$(version)/*"",
""target"": ""MasterData /$(version)/"",
""contentType"": ""MasterData""
},
]
}")
},
{ "/test/IoTData/MasterData/1.0.0IoT.json", new CmfMockJsonData(
@"{
""<DM>AutomationProtocol"": {
""1"": {
""Name"": ""TEST_Protocol"",
""Description"": ""TEST_Protocol"",
""Type"":"" ""General"",
""Package"": ""@criticalmanufacturing/connect-iot-driver-test"",
""PackageVersion"": ""test""
}")
},
{ "/test/IoTData/AutomationWorkflowFiles/MasterData/1.0.0/TestWorkflowIoT.json", new CmfMockJsonData(
@"{
""tasks"": [
{
}
],
""converters"": [
{
}
],
""links"": [
{
}
],
""layout"": {
""general"": {
},
""drawers"": {
}
}
}")
}
});
BuildCommand buildCommand = new BuildCommand(fileSystem.FileSystem);
var cmd = new Command("build");
buildCommand.Configure(cmd);
var console = new TestConsole();
cmd.Invoke(new string[] {
"test/Data/"
}, console);
Assert.IsTrue(console.Error != null && !string.IsNullOrEmpty(console.Error.ToString()), $"Json Validator failed for IoT Data Package: {console.Error.ToString()}");
}
[TestMethod]
public void IoTData_Workflow_JsonValidator_FailData()
{
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
{
{ "/test/cmfpackage.json", new CmfMockJsonData(
@"{
""packageId"": ""Cmf.Custom.Package"",
""version"": ""1.1.0"",
""description"": ""This package deploys Critical Manufacturing Customization"",
""packageType"": ""Root"",
""isInstallable"": true,
""isUniqueInstall"": false,
""dependencies"": [
{
""id"": ""Cmf.Custom.Data"",
""version"": ""1.1.0""
},
{
""id"": ""Cmf.Custom.IoT"",
""version"": ""1.1.0""
}
]
}")
},
{ "/test/IoT/cmfpackage.json", new CmfMockJsonData(
@"{
""packageId"": ""Cmf.Custom.IoT"",
""version"": ""1.1.0"",
""description"": ""Cmf Custom Foxconn IoT Package"",
""packageType"": ""Root"",
""isInstallable"": true,
""isUniqueInstall"": false,
""dependencies"": [
{
""id"": ""Cmf.Custom.IoTData"",
""version"": ""1.1.0""
}
]
}")
},
{ "/test/IoTData/cmfpackage.json", new CmfMockJsonData(
@"{
""packageId"": ""Cmf.Custom.IoTData"",
""version"": ""1.1.0"",
""description"": ""Cmf Custom Foxconn IoTData Package"",
""packageType"": ""IoTData"",
""isInstallable"": true,
""isUniqueInstall"": false,
""contentToPack"": [
{
{
""source"": ""MasterData/$(version)/*"",
""target"": ""MasterData /$(version)/"",
""contentType"": ""MasterData""
},
]
}")
},
{ "/test/IoTData/MasterData/1.0.0IoT.json", new CmfMockJsonData(
@"{
""<DM>AutomationProtocol"": {
""1"": {
""Name"": ""TEST_Protocol"",
""Description"": ""TEST_Protocol"",
""Type"":"" ""General"",
""Package"": ""@criticalmanufacturing/connect-iot-driver-test"",
""PackageVersion"": ""test""
}
}
}")
},
{ "/test/IoTData/AutomationWorkflowFiles/MasterData/1.0.0/AutomationWorkflowFiles/TestWorkflowIoT.json", new CmfMockJsonData(
@"{
""tasks"": [
{
}
],
""converters"": [
{
}
],
""links"": [
{
}
],
""layout"": {
""general"": {
},
""drawers"": {
}")
}
});
BuildCommand buildCommand = new BuildCommand(fileSystem.FileSystem);
var cmd = new Command("build");
buildCommand.Configure(cmd);
var console = new TestConsole();
cmd.Invoke(new string[] {
"test/Data/"
}, console);
Assert.IsTrue(console.Error != null && !string.IsNullOrEmpty(console.Error.ToString()), $"Json Validator failed for IoT Data Workflow Package: {console.Error.ToString()}");
}
}
}
| 40.851752 | 184 | 0.343824 | [
"BSD-3-Clause"
] | cesarmeira90/cli | tests/Specs/JsonValidator.cs | 15,156 | C# |
using System;
using FluentFTP.Servers;
using FluentFTP.Helpers;
#if !CORE
using System.Web;
#endif
#if (CORE || NETFX)
using System.Threading;
#endif
#if ASYNC
using System.Threading.Tasks;
#endif
using System.Linq;
namespace FluentFTP {
public partial class FtpClient : IFtpClient, IDisposable {
#region Dereference Link
/// <summary>
/// Recursively dereferences a symbolic link. See the
/// MaximumDereferenceCount property for controlling
/// how deep this method will recurse before giving up.
/// </summary>
/// <param name="item">The symbolic link</param>
/// <returns>FtpListItem, null if the link can't be dereferenced</returns>
public FtpListItem DereferenceLink(FtpListItem item) {
return DereferenceLink(item, MaximumDereferenceCount);
}
/// <summary>
/// Recursively dereferences a symbolic link
/// </summary>
/// <param name="item">The symbolic link</param>
/// <param name="recMax">The maximum depth of recursion that can be performed before giving up.</param>
/// <returns>FtpListItem, null if the link can't be dereferenced</returns>
public FtpListItem DereferenceLink(FtpListItem item, int recMax) {
LogFunc(nameof(DereferenceLink), new object[] { item.FullName, recMax });
var count = 0;
return DereferenceLink(item, recMax, ref count);
}
/// <summary>
/// Dereference a FtpListItem object
/// </summary>
/// <param name="item">The item to dereference</param>
/// <param name="recMax">Maximum recursive calls</param>
/// <param name="count">Counter</param>
/// <returns>FtpListItem, null if the link can't be dereferenced</returns>
private FtpListItem DereferenceLink(FtpListItem item, int recMax, ref int count) {
if (item.Type != FtpFileSystemObjectType.Link) {
throw new FtpException("You can only dereference a symbolic link. Please verify the item type is Link.");
}
if (item.LinkTarget == null) {
throw new FtpException("The link target was null. Please check this before trying to dereference the link.");
}
foreach (var obj in GetListing(item.LinkTarget.GetFtpDirectoryName())) {
if (item.LinkTarget == obj.FullName) {
if (obj.Type == FtpFileSystemObjectType.Link) {
if (++count == recMax) {
return null;
}
return DereferenceLink(obj, recMax, ref count);
}
if (HasFeature(FtpCapability.MDTM)) {
var modify = GetModifiedTime(obj.FullName);
if (modify != DateTime.MinValue) {
obj.Modified = modify;
}
}
if (obj.Type == FtpFileSystemObjectType.File && obj.Size < 0 && HasFeature(FtpCapability.SIZE)) {
obj.Size = GetFileSize(obj.FullName);
}
return obj;
}
}
return null;
}
#if ASYNC
/// <summary>
/// Dereference a FtpListItem object
/// </summary>
/// <param name="item">The item to dereference</param>
/// <param name="recMax">Maximum recursive calls</param>
/// <param name="count">Counter</param>
/// <param name="token">The token that can be used to cancel the entire process</param>
/// <returns>FtpListItem, null if the link can't be dereferenced</returns>
private async Task<FtpListItem> DereferenceLinkAsync(FtpListItem item, int recMax, IntRef count, CancellationToken token = default(CancellationToken)) {
if (item.Type != FtpFileSystemObjectType.Link) {
throw new FtpException("You can only dereference a symbolic link. Please verify the item type is Link.");
}
if (item.LinkTarget == null) {
throw new FtpException("The link target was null. Please check this before trying to dereference the link.");
}
var listing = await GetListingAsync(item.LinkTarget.GetFtpDirectoryName(), token);
foreach (FtpListItem obj in listing) {
if (item.LinkTarget == obj.FullName) {
if (obj.Type == FtpFileSystemObjectType.Link) {
if (++count.Value == recMax) {
return null;
}
return await DereferenceLinkAsync(obj, recMax, count, token);
}
if (HasFeature(FtpCapability.MDTM)) {
var modify = GetModifiedTime(obj.FullName);
if (modify != DateTime.MinValue) {
obj.Modified = modify;
}
}
if (obj.Type == FtpFileSystemObjectType.File && obj.Size < 0 && HasFeature(FtpCapability.SIZE)) {
obj.Size = GetFileSize(obj.FullName);
}
return obj;
}
}
return null;
}
/// <summary>
/// Dereference a <see cref="FtpListItem"/> object asynchronously
/// </summary>
/// <param name="item">The item to dereference</param>
/// <param name="recMax">Maximum recursive calls</param>
/// <param name="token">The token that can be used to cancel the entire process</param>
/// <returns>FtpListItem, null if the link can't be dereferenced</returns>
public Task<FtpListItem> DereferenceLinkAsync(FtpListItem item, int recMax, CancellationToken token = default(CancellationToken)) {
LogFunc(nameof(DereferenceLinkAsync), new object[] { item.FullName, recMax });
var count = new IntRef { Value = 0 };
return DereferenceLinkAsync(item, recMax, count, token);
}
/// <summary>
/// Dereference a <see cref="FtpListItem"/> object asynchronously
/// </summary>
/// <param name="item">The item to dereference</param>
/// <param name="token">The token that can be used to cancel the entire process</param>
/// <returns>FtpListItem, null if the link can't be dereferenced</returns>
public Task<FtpListItem> DereferenceLinkAsync(FtpListItem item, CancellationToken token = default(CancellationToken)) {
return DereferenceLinkAsync(item, MaximumDereferenceCount, token);
}
#endif
#endregion
#region Get File Size
/// <summary>
/// Gets the size of a remote file, in bytes.
/// </summary>
/// <param name="path">The full or relative path of the file</param>
/// <param name="defaultValue">Value to return if there was an error obtaining the file size, or if the file does not exist</param>
/// <returns>The size of the file, or defaultValue if there was a problem.</returns>
public virtual long GetFileSize(string path, long defaultValue = -1) {
// verify args
if (path.IsBlank()) {
throw new ArgumentException("Required parameter is null or blank.", "path");
}
path = path.GetFtpPath();
LogFunc(nameof(GetFileSize), new object[] { path });
if (!HasFeature(FtpCapability.SIZE)) {
return defaultValue;
}
var sizeReply = new FtpSizeReply();
#if !CORE14
lock (m_lock) {
#endif
GetFileSizeInternal(path, sizeReply, defaultValue);
#if !CORE14
}
#endif
return sizeReply.FileSize;
}
/// <summary>
/// Gets the file size of an object, without locking
/// </summary>
private void GetFileSizeInternal(string path, FtpSizeReply sizeReply, long defaultValue) {
long length = defaultValue;
path = path.GetFtpPath();
// Fix #137: Switch to binary mode since some servers don't support SIZE command for ASCII files.
if (_FileSizeASCIINotSupported) {
SetDataTypeNoLock(FtpDataType.Binary);
}
// execute the SIZE command
var reply = Execute("SIZE " + path);
sizeReply.Reply = reply;
if (!reply.Success) {
length = defaultValue;
// Fix #137: FTP server returns 'SIZE not allowed in ASCII mode'
if (!_FileSizeASCIINotSupported && reply.Message.IsKnownError(FtpServerStrings.fileSizeNotInASCII)) {
// set the flag so mode switching is done
_FileSizeASCIINotSupported = true;
// retry getting the file size
GetFileSizeInternal(path, sizeReply, defaultValue);
return;
}
}
else if (!long.TryParse(reply.Message, out length)) {
length = defaultValue;
}
sizeReply.FileSize = length;
}
#if ASYNC
/// <summary>
/// Asynchronously gets the size of a remote file, in bytes.
/// </summary>
/// <param name="path">The full or relative path of the file</param>
/// <param name="defaultValue">Value to return if there was an error obtaining the file size, or if the file does not exist</param>
/// <param name="token">The token that can be used to cancel the entire process</param>
/// <returns>The size of the file, or defaultValue if there was a problem.</returns>
public async Task<long> GetFileSizeAsync(string path, long defaultValue = -1, CancellationToken token = default(CancellationToken)) {
// verify args
if (path.IsBlank()) {
throw new ArgumentException("Required parameter is null or blank.", "path");
}
path = path.GetFtpPath();
LogFunc(nameof(GetFileSizeAsync), new object[] { path, defaultValue });
if (!HasFeature(FtpCapability.SIZE)) {
return defaultValue;
}
FtpSizeReply sizeReply = new FtpSizeReply();
await GetFileSizeInternalAsync(path, defaultValue, token, sizeReply);
return sizeReply.FileSize;
}
/// <summary>
/// Gets the file size of an object, without locking
/// </summary>
private async Task GetFileSizeInternalAsync(string path, long defaultValue, CancellationToken token, FtpSizeReply sizeReply) {
long length = defaultValue;
path = path.GetFtpPath();
// Fix #137: Switch to binary mode since some servers don't support SIZE command for ASCII files.
if (_FileSizeASCIINotSupported) {
await SetDataTypeNoLockAsync(FtpDataType.Binary, token);
}
// execute the SIZE command
var reply = await ExecuteAsync("SIZE " + path, token);
sizeReply.Reply = reply;
if (!reply.Success) {
sizeReply.FileSize = defaultValue;
// Fix #137: FTP server returns 'SIZE not allowed in ASCII mode'
if (!_FileSizeASCIINotSupported && reply.Message.IsKnownError(FtpServerStrings.fileSizeNotInASCII)) {
// set the flag so mode switching is done
_FileSizeASCIINotSupported = true;
// retry getting the file size
await GetFileSizeInternalAsync(path, defaultValue, token, sizeReply);
return;
}
}
else if (!long.TryParse(reply.Message, out length)) {
length = defaultValue;
}
sizeReply.FileSize = length;
return;
}
#endif
#endregion
#region Get Modified Time
/// <summary>
/// Gets the modified time of a remote file.
/// </summary>
/// <param name="path">The full path to the file</param>
/// <returns>The modified time, or <see cref="DateTime.MinValue"/> if there was a problem</returns>
public virtual DateTime GetModifiedTime(string path) {
// verify args
if (path.IsBlank()) {
throw new ArgumentException("Required parameter is null or blank.", "path");
}
path = path.GetFtpPath();
LogFunc(nameof(GetModifiedTime), new object[] { path });
var date = DateTime.MinValue;
FtpReply reply;
#if !CORE14
lock (m_lock) {
#endif
// get modified date of a file
if ((reply = Execute("MDTM " + path)).Success) {
date = reply.Message.ParseFtpDate(this);
date = ConvertDate(date);
}
#if !CORE14
}
#endif
return date;
}
#if ASYNC
/// <summary>
/// Gets the modified time of a remote file asynchronously
/// </summary>
/// <param name="path">The full path to the file</param>
/// <param name="token">The token that can be used to cancel the entire process</param>
/// <returns>The modified time, or <see cref="DateTime.MinValue"/> if there was a problem</returns>
public async Task<DateTime> GetModifiedTimeAsync(string path, CancellationToken token = default(CancellationToken)) {
// verify args
if (path.IsBlank()) {
throw new ArgumentException("Required parameter is null or blank.", "path");
}
path = path.GetFtpPath();
LogFunc(nameof(GetModifiedTimeAsync), new object[] { path });
var date = DateTime.MinValue;
FtpReply reply;
// get modified date of a file
if ((reply = await ExecuteAsync("MDTM " + path, token)).Success) {
date = reply.Message.ParseFtpDate(this);
date = ConvertDate(date);
}
return date;
}
#endif
#endregion
#region Set Modified Time
/// <summary>
/// Changes the modified time of a remote file
/// </summary>
/// <param name="path">The full path to the file</param>
/// <param name="date">The new modified date/time value</param>
public virtual void SetModifiedTime(string path, DateTime date) {
// verify args
if (path.IsBlank()) {
throw new ArgumentException("Required parameter is null or blank.", "path");
}
if (date == null) {
throw new ArgumentException("Required parameter is null or blank.", "date");
}
path = path.GetFtpPath();
LogFunc(nameof(SetModifiedTime), new object[] { path, date });
FtpReply reply;
#if !CORE14
lock (m_lock) {
#endif
// calculate the final date string with the timezone conversion
date = ConvertDate(date, true);
var timeStr = date.GenerateFtpDate();
// set modified date of a file
if ((reply = Execute("MFMT " + timeStr + " " + path)).Success) {
}
#if !CORE14
}
#endif
}
#if ASYNC
/// <summary>
/// Gets the modified time of a remote file asynchronously
/// </summary>
/// <param name="path">The full path to the file</param>
/// <param name="date">The new modified date/time value</param>
/// <param name="token">The token that can be used to cancel the entire process</param>
public async Task SetModifiedTimeAsync(string path, DateTime date, CancellationToken token = default(CancellationToken)) {
// verify args
if (path.IsBlank()) {
throw new ArgumentException("Required parameter is null or blank.", "path");
}
if (date == null) {
throw new ArgumentException("Required parameter is null or blank.", "date");
}
path = path.GetFtpPath();
LogFunc(nameof(SetModifiedTimeAsync), new object[] { path, date });
FtpReply reply;
// calculate the final date string with the timezone conversion
date = ConvertDate(date, true);
var timeStr = date.GenerateFtpDate();
// set modified date of a file
if ((reply = await ExecuteAsync("MFMT " + timeStr + " " + path, token)).Success) {
}
}
#endif
#endregion
}
}
| 30.796009 | 154 | 0.680251 | [
"MIT"
] | Dylan-DutchAndBold/FluentFTP | FluentFTP/Client/FtpClient_FileProperties.cs | 13,891 | C# |
using JustBenchmark.BenchmarkExecutors;
using System;
using System.Reflection;
using System.Threading.Tasks;
namespace JustBenchmark {
/// <summary>
/// Parallel line benchmark for method returns Task
/// </summary>
public class ParallelTaskBenchmarkAttribute : Attribute, IBenchmarkExecutor {
/// <summary>
/// Iteration count
/// </summary>
public int Iteration { get; set; } = 10000;
/// <summary>
/// Parallel degree
/// </summary>
public int Degree { get; set; } = Environment.ProcessorCount;
/// <summary>
/// Initialize
/// </summary>
public ParallelTaskBenchmarkAttribute() {
}
/// <summary>
/// Initialize
/// </summary>
/// <param name="iteration"></param>
public ParallelTaskBenchmarkAttribute(int iteration) {
Iteration = iteration;
}
/// <summary>
/// Initialize
/// </summary>
public ParallelTaskBenchmarkAttribute(int iteration, int degree) {
Iteration = iteration;
Degree = degree;
}
/// <summary>
/// Execute benchmark
/// </summary>
public BenchmarkResult Execute(MethodInfo method, object instance) {
var func = (Func<Task>)method.CreateDelegate(typeof(Func<Task>), instance);
var initialTaskCount = Math.Min(Degree, Iteration);
var totalTaskCount = Iteration - initialTaskCount;
var taskArray = new Task[initialTaskCount];
var result = this.GenericExecute(method, () => {
for (int from = 0, to = taskArray.Length; from < to; ++from) {
taskArray[from] = func();
}
while (totalTaskCount > 0) {
var index = Task.WaitAny(taskArray);
taskArray[index] = func();
--totalTaskCount;
}
Task.WaitAll(taskArray);
});
return result;
}
}
}
| 26.530303 | 79 | 0.63735 | [
"MIT"
] | OldMansClub/JustBenchmark | JustBenchmark/BenchmarkExecutors/ParallelTaskBenchmarkAttribute.cs | 1,753 | C# |
#pragma checksum "..\..\App.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "51D069302E1354B97D588B2282D61C0CBB8F79990C95F9F5818AE1D38FE05F48"
//------------------------------------------------------------------------------
// <auto-generated>
// O código foi gerado por uma ferramenta.
// Versão de Tempo de Execução:4.0.30319.42000
//
// As alterações ao arquivo poderão causar comportamento incorreto e serão perdidas se
// o código for gerado novamente.
// </auto-generated>
//------------------------------------------------------------------------------
using RDAGen;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace RDAGen {
/// <summary>
/// App
/// </summary>
public partial class App : System.Windows.Application {
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
#line 5 "..\..\App.xaml"
this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative);
#line default
#line hidden
}
/// <summary>
/// Application Entry Point.
/// </summary>
[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public static void Main() {
RDAGen.App app = new RDAGen.App();
app.InitializeComponent();
app.Run();
}
}
}
| 32.295775 | 142 | 0.621457 | [
"Unlicense"
] | rcaropreso/RDAGen | RDAGen/obj/Debug/App.g.cs | 2,304 | C# |
// (c) Copyright HutongGames, LLC 2010-2013. All rights reserved.
using UnityEngine;
namespace HutongGames.PlayMaker.Actions
{
[ActionCategory(ActionCategory.Logic)]
[Tooltip("Tests if the value of a string variable has changed. Use this to send an event on change, or store a bool that can be used in other operations.")]
public class StringChanged : FsmStateAction
{
[RequiredField]
[UIHint(UIHint.Variable)]
[Tooltip("The String Variable to test.")]
public FsmString stringVariable;
[Tooltip("Event to send if changed.")]
public FsmEvent changedEvent;
[UIHint(UIHint.Variable)]
[Tooltip("Set to True if changed, otherwise False.")]
public FsmBool storeResult;
string previousValue;
public override void Reset()
{
stringVariable = null;
changedEvent = null;
storeResult = null;
}
public override void OnEnter()
{
if (stringVariable.IsNone)
{
Finish();
return;
}
previousValue = stringVariable.Value;
}
public override void OnUpdate()
{
if (stringVariable.Value != previousValue)
{
storeResult.Value = true;
Fsm.Event(changedEvent);
}
}
}
}
| 22.730769 | 157 | 0.677665 | [
"MIT"
] | aiden-ji/oneButtonBoB | Assets/PlayMaker/Actions/Logic/StringChanged.cs | 1,182 | C# |
using HeadlessSc.Areas.Headless.Models;
namespace HeadlessSc.Pipelines.GetFieldModel
{
public class GetDefaultFieldModelProcessor : IHeadlessGetFieldModelPipeline
{
public void Process(GetFieldModelArgs args)
{
if (args.Result != null || !args.Field.HasValue)
return;
args.Result = new Field {FieldType = args.Field.Type, Value = args.Field.Value};
}
}
} | 30.857143 | 92 | 0.650463 | [
"MIT"
] | BissTalk/vue-headless-sitecore | src/Foundation/code/HeadlessSc/Pipelines/GetFieldModel/GetDefaultFieldModelProcessor.cs | 434 | C# |
using System;
using LanguageExt.TypeClasses;
using System.Diagnostics.Contracts;
namespace LanguageExt.ClassInstances
{
/// <summary>
/// Integer number
/// </summary>
public struct TChar : Eq<char>, Ord<char>, Monoid<char>, Arithmetic<char>
{
public static readonly TChar Inst = default(TChar);
/// <summary>
/// Equality test
/// </summary>
/// <param name="x">The left hand side of the equality operation</param>
/// <param name="y">The right hand side of the equality operation</param>
/// <returns>True if x and y are equal</returns>
[Pure]
public bool Equals(char x, char y) =>
x == y;
/// <summary>
/// Compare two values
/// </summary>
/// <param name="x">Left hand side of the compare operation</param>
/// <param name="y">Right hand side of the compare operation</param>
/// <returns>
/// if x greater than y : 1
///
/// if x less than y : -1
///
/// if x equals y : 0
/// </returns>
[Pure]
public int Compare(char x, char y) =>
x.CompareTo(y);
/// <summary>
/// Monoid empty value (0)
/// </summary>
/// <returns>0</returns>
[Pure]
public char Empty() => (char)0;
/// <summary>
/// Semigroup append (sum)
/// </summary>
/// <param name="x">left hand side of the append operation</param>
/// <param name="y">right hand side of the append operation</param>
/// <returns>x + y</returns>
[Pure]
public char Append(char x, char y) =>
(char)(x + y);
/// <summary>
/// Get the hash-code of the provided value
/// </summary>
/// <returns>Hash code of x</returns>
[Pure]
public int GetHashCode(char x) =>
x.GetHashCode();
[Pure]
public char Plus(char x, char y) =>
(char)(x + y);
[Pure]
public char Subtract(char x, char y) =>
(char)(x - y);
[Pure]
public char Product(char x, char y) =>
(char) (x * y);
[Pure]
public char Negate(char x) =>
(char)(-x);
}
}
| 28.182927 | 81 | 0.494591 | [
"MIT"
] | 1iveowl/language-ext | LanguageExt.Core/ClassInstances/TChar.cs | 2,313 | C# |
namespace Merchello.Core.Gateways
{
using System;
using System.Collections.Generic;
using Models;
using Services;
using Umbraco.Core.Cache;
/// <summary>
/// Defines the GatewayBase
/// </summary>
public abstract class GatewayProviderBase : IProvider
{
#region Fields
/// <summary>
/// The gateway provider settings.
/// </summary>
private readonly IGatewayProviderSettings _gatewayProviderSettings;
/// <summary>
/// The gateway provider service.
/// </summary>
private readonly IGatewayProviderService _gatewayProviderService;
/// <summary>
/// The runtime cache.
/// </summary>
private readonly IRuntimeCacheProvider _runtimeCache;
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="GatewayProviderBase"/> class.
/// </summary>
/// <param name="gatewayProviderService">The <see cref="IGatewayProviderService"/></param>
/// <param name="gatewayProviderSettings">The <see cref="IGatewayProviderSettings"/></param>
/// <param name="runtimeCacheProvider">Umbraco's <see cref="IRuntimeCacheProvider"/></param>
protected GatewayProviderBase(IGatewayProviderService gatewayProviderService, IGatewayProviderSettings gatewayProviderSettings, IRuntimeCacheProvider runtimeCacheProvider)
{
Mandate.ParameterNotNull(gatewayProviderService, "gatewayProviderService");
Mandate.ParameterNotNull(gatewayProviderSettings, "gatewayProvider");
Mandate.ParameterNotNull(runtimeCacheProvider, "runtimeCacheProvider");
_gatewayProviderService = gatewayProviderService;
_gatewayProviderSettings = gatewayProviderSettings;
_runtimeCache = runtimeCacheProvider;
}
/// <summary>
/// Gets the unique Key that will be used
/// </summary>
public Guid Key
{
get { return _gatewayProviderSettings.Key; }
}
/// <summary>
/// Gets the <see cref="IGatewayProviderService"/>
/// </summary>
public IGatewayProviderService GatewayProviderService
{
get { return _gatewayProviderService; }
}
/// <summary>
/// Gets the <see cref="IGatewayProviderSettings"/>
/// </summary>
public virtual IGatewayProviderSettings GatewayProviderSettings
{
get { return _gatewayProviderSettings; }
}
/// <summary>
/// Gets the ExtendedData collection from the <see cref="IGatewayProviderSettings"/>
/// </summary>
public virtual ExtendedDataCollection ExtendedData
{
get { return _gatewayProviderSettings.ExtendedData; }
}
/// <summary>
/// Gets a value indicating whether or not this provider is "activated"
/// </summary>
public virtual bool Activated
{
get { return _gatewayProviderSettings.Activated; }
}
/// <summary>
/// Gets the RuntimeCache
/// </summary>
/// <returns></returns>
protected IRuntimeCacheProvider RuntimeCache
{
get { return _runtimeCache; }
}
/// <summary>
/// Returns a collection of all possible gateway methods associated with this provider
/// </summary>
/// <returns>A collection of <see cref="IGatewayResource"/></returns>
public abstract IEnumerable<IGatewayResource> ListResourcesOffered();
}
} | 34.47619 | 179 | 0.620994 | [
"MIT"
] | cfallesen/Merchello | src/Merchello.Core/Gateways/GatewayProviderBase.cs | 3,622 | C# |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Nest
{
[JsonObject(MemberSerialization.OptIn)]
[JsonConverter(typeof(ReadAsTypeJsonConverter<TypeMapping>))]
public interface ITypeMapping
{
[JsonProperty("dynamic_date_formats")]
IEnumerable<string> DynamicDateFormats { get; set; }
[JsonProperty("date_detection")]
bool? DateDetection { get; set; }
[JsonProperty("numeric_detection")]
bool? NumericDetection { get; set; }
[JsonProperty("transform")]
[JsonConverter(typeof(MappingTransformCollectionJsonConverter))]
IList<IMappingTransform> Transform { get; set; }
[JsonProperty("analyzer")]
string Analyzer { get; set; }
[JsonProperty("search_analyzer")]
string SearchAnalyzer { get; set; }
[JsonProperty("_source")]
ISourceField SourceField { get; set; }
[JsonProperty("_all")]
IAllField AllField { get; set; }
[JsonProperty("_parent")]
IParentField ParentField { get; set; }
[JsonProperty("_routing")]
IRoutingField RoutingField { get; set; }
[JsonProperty("_index")]
IIndexField IndexField { get; set; }
[JsonProperty("_size")]
ISizeField SizeField { get; set; }
[JsonProperty("_timestamp")]
ITimestampField TimestampField { get; set; }
[JsonProperty("_field_names")]
IFieldNamesField FieldNamesField { get; set; }
[JsonProperty("_ttl")]
ITtlField TtlField { get; set; }
[JsonProperty("_meta")]
[JsonConverter(typeof(VerbatimDictionaryKeysJsonConverter))]
FluentDictionary<string, object> Meta { get; set; }
[JsonProperty("dynamic_templates")]
IDynamicTemplateContainer DynamicTemplates { get; set; }
[JsonProperty("dynamic")]
DynamicMapping? Dynamic { get; set; }
[JsonProperty("properties", TypeNameHandling = TypeNameHandling.None)]
IProperties Properties { get; set; }
}
public class TypeMapping : ITypeMapping
{
/// <inheritdoc/>
public IAllField AllField { get; set; }
/// <inheritdoc/>
public string Analyzer { get; set; }
/// <inheritdoc/>
public bool? DateDetection { get; set; }
/// <inheritdoc/>
public DynamicMapping? Dynamic { get; set; }
/// <inheritdoc/>
public IEnumerable<string> DynamicDateFormats { get; set; }
/// <inheritdoc/>
public IDynamicTemplateContainer DynamicTemplates { get; set; }
/// <inheritdoc/>
public IFieldNamesField FieldNamesField { get; set; }
/// <inheritdoc/>
public IIndexField IndexField { get; set; }
/// <inheritdoc/>
public FluentDictionary<string, object> Meta { get; set; }
/// <inheritdoc/>
public bool? NumericDetection { get; set; }
/// <inheritdoc/>
public IParentField ParentField { get; set; }
/// <inheritdoc/>
public IProperties Properties { get; set; }
/// <inheritdoc/>
public IRoutingField RoutingField { get; set; }
/// <inheritdoc/>
public string SearchAnalyzer { get; set; }
/// <inheritdoc/>
public ISizeField SizeField { get; set; }
/// <inheritdoc/>
public ISourceField SourceField { get; set; }
/// <inheritdoc/>
public ITimestampField TimestampField { get; set; }
/// <inheritdoc/>
public IList<IMappingTransform> Transform { get; set; }
/// <inheritdoc/>
public ITtlField TtlField { get; set; }
}
public class TypeMappingDescriptor<T> : DescriptorBase<TypeMappingDescriptor<T>, ITypeMapping>, ITypeMapping
where T : class
{
IAllField ITypeMapping.AllField { get; set; }
string ITypeMapping.Analyzer { get; set; }
bool? ITypeMapping.DateDetection { get; set; }
DynamicMapping? ITypeMapping.Dynamic { get; set; }
IEnumerable<string> ITypeMapping.DynamicDateFormats { get; set; }
IDynamicTemplateContainer ITypeMapping.DynamicTemplates { get; set; }
IFieldNamesField ITypeMapping.FieldNamesField { get; set; }
IIndexField ITypeMapping.IndexField { get; set; }
FluentDictionary<string, object> ITypeMapping.Meta { get; set; }
bool? ITypeMapping.NumericDetection { get; set; }
IParentField ITypeMapping.ParentField { get; set; }
IProperties ITypeMapping.Properties { get; set; }
IRoutingField ITypeMapping.RoutingField { get; set; }
string ITypeMapping.SearchAnalyzer { get; set; }
ISizeField ITypeMapping.SizeField { get; set; }
ISourceField ITypeMapping.SourceField { get; set; }
ITimestampField ITypeMapping.TimestampField { get; set; }
IList<IMappingTransform> ITypeMapping.Transform { get; set; }
ITtlField ITypeMapping.TtlField { get; set; }
/// <summary>
/// Convenience method to map as much as it can based on ElasticType attributes set on the type.
/// <pre>This method also automatically sets up mappings for known values types (int, long, double, datetime, etcetera)</pre>
/// <pre>Class types default to object and Enums to int</pre>
/// <pre>Later calls can override whatever is set is by this call.</pre>
/// </summary>
public TypeMappingDescriptor<T> AutoMap(IPropertyVisitor visitor = null, int maxRecursion = 0) =>
Assign(a => a.Properties = new PropertyWalker(typeof(T), visitor, maxRecursion).GetProperties());
/// <inheritdoc/>
public TypeMappingDescriptor<T> AutoMap(int maxRecursion) => AutoMap(null, maxRecursion);
/// <inheritdoc/>
public TypeMappingDescriptor<T> Dynamic(DynamicMapping dynamic) => Assign(a => a.Dynamic = dynamic);
/// <inheritdoc/>
public TypeMappingDescriptor<T> Dynamic(bool dynamic = true) => this.Dynamic(dynamic ? DynamicMapping.Allow : DynamicMapping.Ignore);
/// <inheritdoc/>
public TypeMappingDescriptor<T> Parent(TypeName parentType) => Assign(a => a.ParentField = new ParentField { Type = parentType });
/// <inheritdoc/>
public TypeMappingDescriptor<T> Parent<TOther>() where TOther : class => Assign(a => a.ParentField = new ParentField { Type = typeof(TOther) });
/// <inheritdoc/>
public TypeMappingDescriptor<T> Analyzer(string analyzer) => Assign(a => a.Analyzer = analyzer);
/// <inheritdoc/>
public TypeMappingDescriptor<T> SearchAnalyzer(string searchAnalyzer)=> Assign(a => a.SearchAnalyzer = searchAnalyzer);
/// <inheritdoc/>
public TypeMappingDescriptor<T> AllField(Func<AllFieldDescriptor, AllFieldDescriptor> allFieldSelector) => Assign(a => a.AllField = allFieldSelector?.Invoke(new AllFieldDescriptor()));
/// <inheritdoc/>
public TypeMappingDescriptor<T> IndexField(Func<IndexFieldDescriptor, IndexFieldDescriptor> indexFieldSelector) => Assign(a => a.IndexField = indexFieldSelector?.Invoke(new IndexFieldDescriptor()));
/// <inheritdoc/>
public TypeMappingDescriptor<T> SizeField(Func<SizeFieldDescriptor, SizeFieldDescriptor> sizeFieldSelector) => Assign(a => a.SizeField = sizeFieldSelector?.Invoke(new SizeFieldDescriptor()));
/// <inheritdoc/>
public TypeMappingDescriptor<T> SourceField(Func<SourceFieldDescriptor, SourceFieldDescriptor> sourceFieldSelector) => Assign(a => a.SourceField = sourceFieldSelector?.Invoke(new SourceFieldDescriptor()));
/// <inheritdoc/>
public TypeMappingDescriptor<T> DisableSizeField(bool disabled = true) => Assign(a => a.SizeField = new SizeField { Enabled = !disabled });
/// <inheritdoc/>
public TypeMappingDescriptor<T> DisableIndexField(bool disabled = true) => Assign(a => a.IndexField = new IndexField { Enabled = !disabled });
/// <inheritdoc/>
public TypeMappingDescriptor<T> DynamicDateFormats(IEnumerable<string> dateFormats) => Assign(a => a.DynamicDateFormats = dateFormats);
/// <inheritdoc/>
public TypeMappingDescriptor<T> DateDetection(bool detect = true) => Assign(a => a.DateDetection = detect);
/// <inheritdoc/>
public TypeMappingDescriptor<T> NumericDetection(bool detect = true) => Assign(a => a.NumericDetection = detect);
/// <inheritdoc/>
public TypeMappingDescriptor<T> Transform(IEnumerable<IMappingTransform> transforms) => Assign(a => a.Transform = transforms.ToListOrNullIfEmpty());
/// <inheritdoc/>
public TypeMappingDescriptor<T> Transform(Func<MappingTransformsDescriptor, IPromise<IList<IMappingTransform>>> selector) =>
Assign(a => a.Transform = selector?.Invoke(new MappingTransformsDescriptor())?.Value);
/// <inheritdoc/>
public TypeMappingDescriptor<T> RoutingField(Func<RoutingFieldDescriptor<T>, IRoutingField> routingMapper) => Assign(a => a.RoutingField = routingMapper?.Invoke(new RoutingFieldDescriptor<T>()));
/// <inheritdoc/>
public TypeMappingDescriptor<T> TimestampField(Func<TimestampFieldDescriptor<T>, ITimestampField> timestampMapper) => Assign(a => a.TimestampField = timestampMapper?.Invoke(new TimestampFieldDescriptor<T>()));
/// <inheritdoc/>
public TypeMappingDescriptor<T> FieldNamesField(Func<FieldNamesFieldDescriptor<T>, IFieldNamesField> fieldNamesMapper) => Assign(a => a.FieldNamesField = fieldNamesMapper.Invoke(new FieldNamesFieldDescriptor<T>()));
/// <inheritdoc/>
public TypeMappingDescriptor<T> TtlField(Func<TtlFieldDescriptor, ITtlField> ttlFieldMapper) => Assign(a => a.TtlField = ttlFieldMapper?.Invoke(new TtlFieldDescriptor()));
/// <inheritdoc/>
public TypeMappingDescriptor<T> Meta(Func<FluentDictionary<string, object>, FluentDictionary<string, object>> metaSelector) => Assign(a => a.Meta = metaSelector(new FluentDictionary<string, object>()));
public TypeMappingDescriptor<T> Properties(Func<PropertiesDescriptor<T>, PropertiesDescriptor<T>> propertiesSelector) =>
Assign(a => a.Properties = propertiesSelector?.Invoke(new PropertiesDescriptor<T>(Self.Properties))?.PromisedValue);
/// <inheritdoc/>
public TypeMappingDescriptor<T> DynamicTemplates(Func<DynamicTemplateContainerDescriptor<T>, IPromise<IDynamicTemplateContainer>> dynamicTemplatesSelector) =>
Assign(a => a.DynamicTemplates = dynamicTemplatesSelector?.Invoke(new DynamicTemplateContainerDescriptor<T>())?.Value);
}
}
| 43.178571 | 217 | 0.734595 | [
"Apache-2.0"
] | lukapor/NEST | src/Nest/Mapping/TypeMapping.cs | 9,674 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the swf-2012-01-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.SimpleWorkflow.Model
{
/// <summary>
/// Provides details of the <code>RequestCancelExternalWorkflowExecutionInitiated</code>
/// event.
/// </summary>
public partial class RequestCancelExternalWorkflowExecutionInitiatedEventAttributes
{
private string _control;
private long? _decisionTaskCompletedEventId;
private string _runId;
private string _workflowId;
/// <summary>
/// Gets and sets the property Control.
/// <para>
/// Optional data attached to the event that can be used by the decider in subsequent
/// workflow tasks.
/// </para>
/// </summary>
public string Control
{
get { return this._control; }
set { this._control = value; }
}
// Check to see if Control property is set
internal bool IsSetControl()
{
return this._control != null;
}
/// <summary>
/// Gets and sets the property DecisionTaskCompletedEventId.
/// <para>
/// The id of the <code>DecisionTaskCompleted</code> event corresponding to the decision
/// task that resulted in the <code>RequestCancelExternalWorkflowExecution</code> decision
/// for this cancellation request. This information can be useful for diagnosing problems
/// by tracing back the cause of events.
/// </para>
/// </summary>
public long DecisionTaskCompletedEventId
{
get { return this._decisionTaskCompletedEventId.GetValueOrDefault(); }
set { this._decisionTaskCompletedEventId = value; }
}
// Check to see if DecisionTaskCompletedEventId property is set
internal bool IsSetDecisionTaskCompletedEventId()
{
return this._decisionTaskCompletedEventId.HasValue;
}
/// <summary>
/// Gets and sets the property RunId.
/// <para>
/// The <code>runId</code> of the external workflow execution to be canceled.
/// </para>
/// </summary>
public string RunId
{
get { return this._runId; }
set { this._runId = value; }
}
// Check to see if RunId property is set
internal bool IsSetRunId()
{
return this._runId != null;
}
/// <summary>
/// Gets and sets the property WorkflowId.
/// <para>
/// The <code>workflowId</code> of the external workflow execution to be canceled.
/// </para>
/// </summary>
public string WorkflowId
{
get { return this._workflowId; }
set { this._workflowId = value; }
}
// Check to see if WorkflowId property is set
internal bool IsSetWorkflowId()
{
return this._workflowId != null;
}
}
} | 32.313559 | 101 | 0.612379 | [
"Apache-2.0"
] | ermshiperete/aws-sdk-net | AWSSDK_DotNet35/Amazon.SimpleWorkflow/Model/RequestCancelExternalWorkflowExecutionInitiatedEventAttributes.cs | 3,813 | C# |
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
namespace NetCoreKit.Infrastructure.AspNetCore.Configuration
{
public static class ConfigurationExtensions
{
public static string GetHostUri(this IConfiguration config, IHostingEnvironment env, string groupName)
{
return env.IsDevelopment() ? config.GetExternalHostUri(groupName) : config.GetInternalHostUri(groupName);
}
public static string GetInternalHostUri(this IConfiguration config, string groupName)
{
var group = config
.GetSection("Hosts")
?.GetSection("Internals")
?.GetSection(groupName);
var serviceDnsName = group.GetValue<string>("ServiceName").ToUpperInvariant();
var serviceHost = $"{Environment.GetEnvironmentVariable($"{serviceDnsName}_SERVICE_HOST")}";
var servicePort = $"{Environment.GetEnvironmentVariable($"{serviceDnsName}_SERVICE_PORT")}";
var basePath = $"{group.GetValue("BasePath", string.Empty)}";
return $"http://{serviceHost}:{servicePort}{basePath}";
}
public static string GetExternalHostUri(this IConfiguration config, string groupName)
{
return config
.GetSection("Hosts")
?.GetSection("Externals")
?.GetSection(groupName)
?.GetValue<string>("Uri");
}
public static string GetBasePath(this IConfiguration config)
{
return config
.GetSection("Hosts")
?.GetValue<string>("BasePath");
}
public static string GetExternalCurrentHostUri(this IConfiguration config)
{
return config
.GetSection("Hosts")
?.GetSection("Externals")
?.GetValue<string>("CurrentUri");
}
}
}
| 32.092593 | 111 | 0.683208 | [
"MIT"
] | toanvo/netcorekit | src/NetCoreKit.Infrastructure.AspNetCore/Configuration/ConfigurationExtensions.cs | 1,733 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using ILRuntime.CLR.TypeSystem;
using ILRuntime.CLR.Method;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.Runtime.Intepreter;
using ILRuntime.Runtime.Stack;
using ILRuntime.Reflection;
using ILRuntime.CLR.Utils;
namespace ILRuntime.Runtime.Generated
{
unsafe class ETModel_HotfixHelper_Binding
{
public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)
{
BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodBase method;
Type[] args;
Type type = typeof(ETModel.HotfixHelper);
args = new Type[]{};
method = type.GetMethod("GetTypes", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, GetTypes_0);
}
static StackObject* GetTypes_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* __ret = ILIntepreter.Minus(__esp, 0);
var result_of_this_method = ETModel.HotfixHelper.GetTypes();
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
}
}
| 30.729167 | 139 | 0.678644 | [
"MIT"
] | InMyBload/et6.0-ilruntime | Unity/Assets/Clod/ILBinding/ETModel_HotfixHelper_Binding.cs | 1,475 | C# |
using MediatR;
using StructureMap;
namespace SFA.DAS.EmployerAccounts.DependencyResolution
{
public class MediatorRegistry : Registry
{
public MediatorRegistry()
{
For<IMediator>().Use<Mediator>();
For<MultiInstanceFactory>().Use<MultiInstanceFactory>(c => c.GetAllInstances);
For<SingleInstanceFactory>().Use<SingleInstanceFactory>(c => c.GetInstance);
}
}
} | 28.866667 | 90 | 0.655889 | [
"MIT"
] | SkillsFundingAgency/das-employeraccounts | src/SFA.DAS.EmployerAccounts/DependencyResolution/MediatorRegistry.cs | 435 | C# |
/**
* Autogenerated by Thrift Compiler (0.9.1)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Thrift;
using Thrift.Collections;
using System.Runtime.Serialization;
using Thrift.Protocol;
using Thrift.Transport;
namespace LineSharp.Datatypes
{
#if !SILVERLIGHT
[Serializable]
#endif
public partial class ProductList : TBase
{
private bool _hasNext;
private long _bannerSequence;
private ProductBannerLinkType _bannerTargetType;
private string _bannerTargetPath;
private List<Product> _productList_;
private string _bannerLang;
public bool HasNext
{
get
{
return _hasNext;
}
set
{
__isset.hasNext = true;
this._hasNext = value;
}
}
public long BannerSequence
{
get
{
return _bannerSequence;
}
set
{
__isset.bannerSequence = true;
this._bannerSequence = value;
}
}
/// <summary>
///
/// <seealso cref="ProductBannerLinkType"/>
/// </summary>
public ProductBannerLinkType BannerTargetType
{
get
{
return _bannerTargetType;
}
set
{
__isset.bannerTargetType = true;
this._bannerTargetType = value;
}
}
public string BannerTargetPath
{
get
{
return _bannerTargetPath;
}
set
{
__isset.bannerTargetPath = true;
this._bannerTargetPath = value;
}
}
public List<Product> ProductList_
{
get
{
return _productList_;
}
set
{
__isset.productList_ = true;
this._productList_ = value;
}
}
public string BannerLang
{
get
{
return _bannerLang;
}
set
{
__isset.bannerLang = true;
this._bannerLang = value;
}
}
public Isset __isset;
#if !SILVERLIGHT
[Serializable]
#endif
public struct Isset {
public bool hasNext;
public bool bannerSequence;
public bool bannerTargetType;
public bool bannerTargetPath;
public bool productList_;
public bool bannerLang;
}
public ProductList() {
}
public void Read (TProtocol iprot)
{
TField field;
iprot.ReadStructBegin();
while (true)
{
field = iprot.ReadFieldBegin();
if (field.Type == TType.Stop) {
break;
}
switch (field.ID)
{
case 1:
if (field.Type == TType.Bool) {
HasNext = iprot.ReadBool();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 4:
if (field.Type == TType.I64) {
BannerSequence = iprot.ReadI64();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 5:
if (field.Type == TType.I32) {
BannerTargetType = (ProductBannerLinkType)iprot.ReadI32();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 6:
if (field.Type == TType.String) {
BannerTargetPath = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 7:
if (field.Type == TType.List) {
{
ProductList_ = new List<Product>();
TList _list34 = iprot.ReadListBegin();
for( int _i35 = 0; _i35 < _list34.Count; ++_i35)
{
Product _elem36 = new Product();
_elem36 = new Product();
_elem36.Read(iprot);
ProductList_.Add(_elem36);
}
iprot.ReadListEnd();
}
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 8:
if (field.Type == TType.String) {
BannerLang = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
default:
TProtocolUtil.Skip(iprot, field.Type);
break;
}
iprot.ReadFieldEnd();
}
iprot.ReadStructEnd();
}
public void Write(TProtocol oprot) {
TStruct struc = new TStruct("ProductList");
oprot.WriteStructBegin(struc);
TField field = new TField();
if (__isset.hasNext) {
field.Name = "hasNext";
field.Type = TType.Bool;
field.ID = 1;
oprot.WriteFieldBegin(field);
oprot.WriteBool(HasNext);
oprot.WriteFieldEnd();
}
if (__isset.bannerSequence) {
field.Name = "bannerSequence";
field.Type = TType.I64;
field.ID = 4;
oprot.WriteFieldBegin(field);
oprot.WriteI64(BannerSequence);
oprot.WriteFieldEnd();
}
if (__isset.bannerTargetType) {
field.Name = "bannerTargetType";
field.Type = TType.I32;
field.ID = 5;
oprot.WriteFieldBegin(field);
oprot.WriteI32((int)BannerTargetType);
oprot.WriteFieldEnd();
}
if (BannerTargetPath != null && __isset.bannerTargetPath) {
field.Name = "bannerTargetPath";
field.Type = TType.String;
field.ID = 6;
oprot.WriteFieldBegin(field);
oprot.WriteString(BannerTargetPath);
oprot.WriteFieldEnd();
}
if (ProductList_ != null && __isset.productList_) {
field.Name = "productList_";
field.Type = TType.List;
field.ID = 7;
oprot.WriteFieldBegin(field);
{
oprot.WriteListBegin(new TList(TType.Struct, ProductList_.Count));
foreach (Product _iter37 in ProductList_)
{
_iter37.Write(oprot);
}
oprot.WriteListEnd();
}
oprot.WriteFieldEnd();
}
if (BannerLang != null && __isset.bannerLang) {
field.Name = "bannerLang";
field.Type = TType.String;
field.ID = 8;
oprot.WriteFieldBegin(field);
oprot.WriteString(BannerLang);
oprot.WriteFieldEnd();
}
oprot.WriteFieldStop();
oprot.WriteStructEnd();
}
public override string ToString() {
StringBuilder sb = new StringBuilder("ProductList(");
sb.Append("HasNext: ");
sb.Append(HasNext);
sb.Append(",BannerSequence: ");
sb.Append(BannerSequence);
sb.Append(",BannerTargetType: ");
sb.Append(BannerTargetType);
sb.Append(",BannerTargetPath: ");
sb.Append(BannerTargetPath);
sb.Append(",ProductList_: ");
sb.Append(ProductList_);
sb.Append(",BannerLang: ");
sb.Append(BannerLang);
sb.Append(")");
return sb.ToString();
}
}
}
| 24.506897 | 76 | 0.536232 | [
"MIT"
] | Banandana/LineSharp | LINE/gen-csharp/ProductList.cs | 7,107 | C# |
using System;
using Org.BouncyCastle.Crypto.Parameters;
namespace Org.BouncyCastle.Crypto.Modes
{
/**
* implements a Output-FeedBack (OFB) mode on top of a simple cipher.
*/
public class OfbBlockCipher
: IBlockCipher
{
private byte[] IV;
private byte[] ofbV;
private byte[] ofbOutV;
private readonly int blockSize;
private readonly IBlockCipher cipher;
/**
* Basic constructor.
*
* @param cipher the block cipher to be used as the basis of the
* feedback mode.
* @param blockSize the block size in bits (note: a multiple of 8)
*/
public OfbBlockCipher(
IBlockCipher cipher,
int blockSize)
{
this.cipher = cipher;
this.blockSize = blockSize / 8;
this.IV = new byte[cipher.GetBlockSize()];
this.ofbV = new byte[cipher.GetBlockSize()];
this.ofbOutV = new byte[cipher.GetBlockSize()];
}
/**
* return the underlying block cipher that we are wrapping.
*
* @return the underlying block cipher that we are wrapping.
*/
public IBlockCipher GetUnderlyingCipher()
{
return cipher;
}
/**
* Initialise the cipher and, possibly, the initialisation vector (IV).
* If an IV isn't passed as part of the parameter, the IV will be all zeros.
* An IV which is too short is handled in FIPS compliant fashion.
*
* @param forEncryption if true the cipher is initialised for
* encryption, if false for decryption.
* @param param the key and other data required by the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public void Init(
bool forEncryption, //ignored by this OFB mode
ICipherParameters parameters)
{
if (parameters is ParametersWithIV)
{
ParametersWithIV ivParam = (ParametersWithIV)parameters;
byte[] iv = ivParam.GetIV();
if (iv.Length < IV.Length)
{
// prepend the supplied IV with zeros (per FIPS PUB 81)
Array.Copy(iv, 0, IV, IV.Length - iv.Length, iv.Length);
for (int i = 0; i < IV.Length - iv.Length; i++)
{
IV[i] = 0;
}
}
else
{
Array.Copy(iv, 0, IV, 0, IV.Length);
}
parameters = ivParam.Parameters;
}
Reset();
cipher.Init(true, parameters);
}
/**
* return the algorithm name and mode.
*
* @return the name of the underlying algorithm followed by "/OFB"
* and the block size in bits
*/
public string AlgorithmName
{
get { return cipher.AlgorithmName + "/OFB" + (blockSize * 8); }
}
public bool IsPartialBlockOkay
{
get { return true; }
}
/**
* return the block size we are operating at (in bytes).
*
* @return the block size we are operating at (in bytes).
*/
public int GetBlockSize()
{
return blockSize;
}
/**
* Process one block of input from the array in and write it to
* the out array.
*
* @param in the array containing the input data.
* @param inOff offset into the in array the data starts at.
* @param out the array the output data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
if ((inOff + blockSize) > input.Length)
{
throw new DataLengthException("input buffer too short");
}
if ((outOff + blockSize) > output.Length)
{
throw new DataLengthException("output buffer too short");
}
cipher.ProcessBlock(ofbV, 0, ofbOutV, 0);
//
// XOR the ofbV with the plaintext producing the cipher text (and
// the next input block).
//
for (int i = 0; i < blockSize; i++)
{
output[outOff + i] = (byte)(ofbOutV[i] ^ input[inOff + i]);
}
//
// change over the input block.
//
Array.Copy(ofbV, blockSize, ofbV, 0, ofbV.Length - blockSize);
Array.Copy(ofbOutV, 0, ofbV, ofbV.Length - blockSize, blockSize);
return blockSize;
}
/**
* reset the feedback vector back to the IV and reset the underlying
* cipher.
*/
public void Reset()
{
Array.Copy(IV, 0, ofbV, 0, IV.Length);
cipher.Reset();
}
}
}
| 30.938547 | 84 | 0.506501 | [
"BSD-3-Clause"
] | GaloisInc/hacrypto | src/C#/BouncyCastle/BouncyCastle-1.7/crypto/src/crypto/modes/OfbBlockCipher.cs | 5,538 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Net;
namespace NeaProgramServer {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
const uint WM_KEYDOWN = 0x0100;
private const int Port = 17771;
private TcpListener tcpListener;
private Thread listenThread;
private static UnicodeEncoding encoder = new UnicodeEncoding();
private bool ListeningStarted;
public MainWindow() {
InitializeComponent();
css = new Process();
css.StartInfo.FileName = "C:\\css\\srcds.exe";
css.StartInfo.Arguments = "-console -game cstrike -insecure +maxplayers 22 +map de_dust";
minecraft = new Process();
minecraft.StartInfo.WorkingDirectory = "C:\\Users\\Kristjan\\Dropbox\\Spil\\Minecraft server (2)";
minecraft.StartInfo.FileName = "serverjar.bat";
terraria = new Process();
terraria.StartInfo.WorkingDirectory = "C:\\Users\\Kristjan\\Dropbox\\Spil\\Terraria";
terraria.StartInfo.FileName = "startLundion.bat";
StartListening();
}
Process css;
Process minecraft;
Process terraria;
private void buttoncss_Click(object sender, RoutedEventArgs e) {
if (((string)buttoncss.Content) == "Start") {
StartProcess(css, statuscss, buttoncss);
}
else {
StopProcess(css, statuscss, buttoncss);
}
}
private void buttonminecraft_Click(object sender, RoutedEventArgs e) {
if (((string)buttonminecraft.Content) == "Start") {
StartProcess(minecraft, statusminecraft, buttonminecraft);
}
else {
IntPtr handle = minecraft.MainWindowHandle;
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.S, 0);
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.T, 0);
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.O, 0);
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.P, 0);
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.Enter, 0);
minecraft.WaitForExit(5000);
StopProcess(minecraft, statusminecraft, buttonminecraft);
}
}
private void buttonterraria_Click(object sender, RoutedEventArgs e) {
if (((string)buttonterraria.Content) == "Start") {
StartProcess(terraria, statusterraria, buttonterraria);
}
else {
IntPtr handle = terraria.MainWindowHandle;
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.E, 0);
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.X, 0);
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.I, 0);
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.T, 0);
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.Enter, 0);
terraria.WaitForExit(5000);
StopProcess(terraria, statusterraria, buttonterraria);
}
}
private void StartProcess(Process process, Label label, Button button) {
bool running = false;
try {
Process.GetProcessById(process.Id);
running = true;
} catch { }
if (!running) {
process.Start();
}
label.Content = "CURRENTLY RUNNING";
button.Content = "Stop";
}
private void StopProcess(Process process, Label label, Button button) {
bool running = false;
try {
Process.GetProcessById(process.Id);
running = true;
}
catch { }
if (running) {
process.CloseMainWindow();
process.Close();
}
label.Content = "CURRENTLY STOPPED";
button.Content = "Start";
}
private void AwaitCommunication(object client) {
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
while (true) {
String message = "";
try { //blocks until a client sends a message
message = ReadMessage(clientStream);
}
catch { //a socket error has occured
break;
}
if (message == "")
break;
switch (message) {
case "css-start":
Dispatcher.Invoke(() => { StartProcess(css, statuscss, buttoncss); });
break;
case "css-stop":
Dispatcher.Invoke(() => { StopProcess(css, statuscss, buttoncss); });
break;
case "minecraft-start":
Dispatcher.Invoke(() => { StartProcess(minecraft, statusminecraft, buttonminecraft); });
break;
case "minecraft-stop":
Dispatcher.Invoke(() => {
IntPtr handle = minecraft.MainWindowHandle;
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.S, 0);
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.T, 0);
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.O, 0);
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.P, 0);
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.Enter, 0);
minecraft.WaitForExit(5000);
StopProcess(minecraft, statusminecraft, buttonminecraft);
});
break;
case "terraria-start":
Dispatcher.Invoke(() => { StartProcess(terraria, statusterraria, buttonterraria); });
break;
case "terraria-stop":
Dispatcher.Invoke(() => {
IntPtr handle = terraria.MainWindowHandle;
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.E, 0);
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.X, 0);
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.I, 0);
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.T, 0);
PostMessage(handle, WM_KEYDOWN, (int)System.Windows.Forms.Keys.Enter, 0);
terraria.WaitForExit(5000);
StopProcess(terraria, statusterraria, buttonterraria);
});
break;
case "status":
string response = "";
bool running = false;
try {
Process.GetProcessById(css.Id);
running = true;
}
catch { }
response += running ? "1" : "0";
running = false;
try {
Process.GetProcessById(minecraft.Id);
running = true;
}
catch { }
response += running ? "1" : "0";
running = false;
try {
Process.GetProcessById(terraria.Id);
running = true;
}
catch { }
response += running ? "1" : "0";
SendMessage(tcpClient, response);
break;
default:
break;
}
}
tcpClient.Close();
}
private void StartListening() {
tcpListener = new TcpListener(IPAddress.Any, Port);
listenThread = new Thread(new ThreadStart(ListenForClients));
ListeningStarted = true;
listenThread.Start();
}
private void StopListening() {
ListeningStarted = false;
tcpListener.Stop();
listenThread.Join(20);
if (listenThread.IsAlive)
listenThread.Abort();
}
private void ListenForClients() {
tcpListener.Start();
while (ListeningStarted) {
try {
TcpClient client = this.tcpListener.AcceptTcpClient(); //blocks until a client has connected to the server
Thread clientThread = new Thread(new ParameterizedThreadStart(AwaitCommunication));
clientThread.Start(client);
}
catch { }
}
this.tcpListener.Stop();
}
public void SendMessage(TcpClient client, string messagebody) {
byte[] message = encoder.GetBytes(messagebody);
byte[] sizeinfo = new byte[4];
//could optionally call BitConverter.GetBytes(data.length);
sizeinfo[0] = (byte)message.Length;
sizeinfo[1] = (byte)(message.Length >> 8);
sizeinfo[2] = (byte)(message.Length >> 16);
sizeinfo[3] = (byte)(message.Length >> 24);
client.GetStream().Write(sizeinfo, 0, 4);
client.GetStream().Write(message, 0, message.Length);
client.GetStream().Flush();
}
static string ReadMessage(NetworkStream stream) {
byte[] sizeinfo = new byte[4];
//read the size of the message
int totalread = 0, currentread = 0;
currentread = totalread = stream.Read(sizeinfo, 0, 4);// socket.Receive(sizeinfo);
while (totalread < sizeinfo.Length && currentread > 0) {
currentread = stream.Read(sizeinfo,
totalread, //offset into the buffer
sizeinfo.Length - totalread //max amount to read
);
totalread += currentread;
}
int messagesize = 0;
//could optionally call BitConverter.ToInt32(sizeinfo, 0);
messagesize |= sizeinfo[0];
messagesize |= (((int)sizeinfo[1]) << 8);
messagesize |= (((int)sizeinfo[2]) << 16);
messagesize |= (((int)sizeinfo[3]) << 24);
//create a byte array of the correct size
//note: there really should be a size restriction on
// messagesize because a user could send
// Int32.MaxValue and cause an OutOfMemoryException
// on the receiving side. maybe consider using a short instead
// or just limit the size to some reasonable value
byte[] data = new byte[messagesize];
//read the first chunk of data
totalread = 0;
currentread = totalread = stream.Read(data,
totalread, //offset into the buffer
data.Length - totalread //max amount to read
);
//if we didn't get the entire message, read some more until we do
while (totalread < messagesize && currentread > 0) {
currentread = stream.Read(data,
totalread, //offset into the buffer
data.Length - totalread //max amount to read
);
totalread += currentread;
}
return encoder.GetString(data, 0, totalread);
}
private void Window_Closed(object sender, EventArgs e) {
StopListening();
}
}
}
| 31.298742 | 111 | 0.669848 | [
"BSD-3-Clause"
] | Armienn/Nea | NeaProgramServer/MainWindow.xaml.cs | 9,955 | C# |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT
namespace NLog.LayoutRenderers
{
using System;
using System.Text;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// The machine name that the process is running on.
/// </summary>
[LayoutRenderer("machinename")]
[AppDomainFixedOutput]
[ThreadAgnostic]
public class MachineNameLayoutRenderer : LayoutRenderer
{
internal string MachineName { get; private set; }
/// <summary>
/// Initializes the layout renderer.
/// </summary>
protected override void InitializeLayoutRenderer()
{
base.InitializeLayoutRenderer();
try
{
this.MachineName = Environment.MachineName;
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Error getting machine name.");
if (exception.MustBeRethrown())
{
throw;
}
this.MachineName = string.Empty;
}
}
/// <summary>
/// Renders the machine name and appends it to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
builder.Append(this.MachineName);
}
}
}
#endif
| 35.966667 | 105 | 0.662033 | [
"BSD-3-Clause"
] | 0xC057A/NLog | src/NLog/LayoutRenderers/MachineNameLayoutRenderer.cs | 3,237 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace PersonalInfoRegistration.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 35.933333 | 151 | 0.587199 | [
"MIT"
] | KrimReaper/L0002B | Task-3/PersonalInfoRegistration/Properties/Settings.Designer.cs | 1,080 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using OpenQA.Selenium;
namespace Selenium.Internal.SeleniumEmulation
{
internal class GetCookieByName : SeleneseCommand
{
protected override object HandleSeleneseCommand(IWebDriver driver, string locator, string value)
{
Cookie cookie = driver.Manage().GetCookieNamed(locator);
return cookie == null ? null : cookie.Value;
}
}
}
| 27.882353 | 105 | 0.672996 | [
"Apache-2.0"
] | hugs/selenium | selenium/src/csharp/WebdriverBackedSelenium/Internal/SeleniumEmulation/GetCookieByName.cs | 476 | C# |
// <copyright file="Models.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
namespace Microsoft.Azure.Networking.Infrastructure.RingMaster.Tools.FiniteModelCheckerUnitTest.GeneralizedDieHard
{
using System.Collections.Generic;
using FiniteModelChecker;
/// <summary>
/// Runs various models.
/// </summary>
public static class Models
{
/// <summary>
/// The basic problem, like from the movie.
/// </summary>
/// <returns>The model check result.</returns>
public static ModelCheckReport<Constants, Variables> CheckBasic()
{
List<int> jugs = new List<int> { 1, 2 };
Dictionary<int, int> jugCapacities = new Dictionary<int, int>
{
[jugs[0]] = 3,
[jugs[1]] = 5
};
Constants constants = new Constants(jugs, jugCapacities);
IInitialStates<Constants, Variables> init = new InitialStateGenerator();
INextStateRelation<Constants, Variables> nextStateRelation = BuildNextStateRelation(constants);
ISafetyInvariant<Constants, Variables> safetyInvariant = new SafetyProperties();
ISafetyInvariant<Constants, Variables> goal = new Goal(4);
return ModelCheck<Constants, Variables>.CheckModel(
constants,
init,
nextStateRelation,
safetyInvariant,
goal);
}
/// <summary>
/// Model-checks a scenario with more jugs.
/// </summary>
/// <returns>The model check result.</returns>
public static ModelCheckReport<Constants, Variables> CheckLarge()
{
List<int> jugs = new List<int> { 1, 2, 3, 4 };
Dictionary<int, int> jugCapacities = new Dictionary<int, int>
{
[jugs[0]] = 3,
[jugs[1]] = 5,
[jugs[2]] = 7,
[jugs[3]] = 9
};
Constants constants = new Constants(jugs, jugCapacities);
IInitialStates<Constants, Variables> init = new InitialStateGenerator();
INextStateRelation<Constants, Variables> nextStateRelation = BuildNextStateRelation(constants);
ISafetyInvariant<Constants, Variables> safetyInvariant = new SafetyProperties();
ISafetyInvariant<Constants, Variables> goal = new Goal(8);
return ModelCheck<Constants, Variables>.CheckModel(
constants,
init,
nextStateRelation,
safetyInvariant,
goal);
}
/// <summary>
/// Model-checks a scenario where the goal is not reachable.
/// </summary>
/// <returns>The model check result.</returns>
public static ModelCheckReport<Constants, Variables> CheckImpossible()
{
List<int> jugs = new List<int> { 1, 2, 3 };
Dictionary<int, int> jugCapacities = new Dictionary<int, int>
{
[jugs[0]] = 2,
[jugs[1]] = 4,
[jugs[2]] = 8,
};
Constants constants = new Constants(jugs, jugCapacities);
IInitialStates<Constants, Variables> init = new InitialStateGenerator();
INextStateRelation<Constants, Variables> nextStateRelation = BuildNextStateRelation(constants);
ISafetyInvariant<Constants, Variables> safetyInvariant = new SafetyProperties();
ISafetyInvariant<Constants, Variables> goal = new Goal(3);
return ModelCheck<Constants, Variables>.CheckModel(
constants,
init,
nextStateRelation,
safetyInvariant,
goal);
}
/// <summary>
/// Builds the full next-state relation.
/// </summary>
/// <param name="constants">The system constants.</param>
/// <returns>The full next-state relation.</returns>
private static INextStateRelation<Constants, Variables> BuildNextStateRelation(Constants constants)
{
var fillJug =
new ExistentialQuantification<int, Constants, Variables>(
constants.Jugs, jug => new FillJug(jug));
var emptyJug =
new ExistentialQuantification<int, Constants, Variables>(
constants.Jugs, jug => new EmptyJug(jug));
var transfer = new ExistentialQuantification<int, Constants, Variables>(
constants.Jugs,
jug1 => new ExistentialQuantification<int, Constants, Variables>(
constants.Jugs,
jug2 => new TransferBetweenJugs(jug1, jug2)));
return new Disjunction<Constants, Variables>(fillJug, emptyJug, transfer);
}
}
} | 40.570248 | 114 | 0.57364 | [
"MIT"
] | Azure/RingMaster | src/Tools/FiniteModelChecker/UnitTest/GeneralizedDieHard/Models.cs | 4,911 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Dapper;
using Hangfire.Console;
using Hangfire.Server;
using HtmlAgilityPack;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Relisten.Api.Models;
using Relisten.Data;
using Relisten.Vendor;
namespace Relisten.Import
{
public class JerryGarciaComImporter : ImporterBase
{
public const string DataSourceName = "jerrygarcia.com";
private IDictionary<string, SetlistShow> existingSetlistShows = new Dictionary<string, SetlistShow>();
private IDictionary<string, SetlistSong> existingSetlistSongs = new Dictionary<string, SetlistSong>();
private IDictionary<string, Tour> existingTours = new Dictionary<string, Tour>();
private IDictionary<string, VenueWithShowCount> existingVenues = new Dictionary<string, VenueWithShowCount>();
private IDictionary<string, DateTime> tourToEndDate = new Dictionary<string, DateTime>();
private IDictionary<string, DateTime> tourToStartDate = new Dictionary<string, DateTime>();
public JerryGarciaComImporter(
DbService db,
SetlistShowService setlistShowService,
VenueService venueService,
TourService tourService,
SetlistSongService setlistSongService,
ILogger<JerryGarciaComImporter> log,
RedisService redisService
) : base(db, redisService)
{
_setlistShowService = setlistShowService;
_venueService = venueService;
_tourService = tourService;
_setlistSongService = setlistSongService;
_log = log;
}
protected SetlistShowService _setlistShowService { get; set; }
protected SetlistSongService _setlistSongService { get; set; }
protected VenueService _venueService { get; set; }
protected TourService _tourService { get; set; }
protected ILogger<JerryGarciaComImporter> _log { get; set; }
public override string ImporterName => "jerrygarcia.com";
public override ImportableData ImportableDataForArtist(Artist artist)
{
return ImportableData.Eras
| ImportableData.SetlistShowsAndSongs
| ImportableData.Tours
| ImportableData.Venues;
}
private string ShowPagesListingUrl(ArtistUpstreamSource src)
{
return
$"https://relisten-grateful-dead-metadata-mirror.s3.amazonaws.com/{src.upstream_identifier}/show_pages.json";
}
private string ShowPageUrl(ArtistUpstreamSource src, string filename)
{
return
$"https://relisten-grateful-dead-metadata-mirror.s3.amazonaws.com/{src.upstream_identifier}/show_pages/{filename}";
}
public override async Task<ImportStats> ImportDataForArtist(Artist artist, ArtistUpstreamSource src,
PerformContext ctx)
{
var stats = new ImportStats();
await PreloadData(artist);
var resp = await http.GetAsync(ShowPagesListingUrl(src));
var showFilesResponse = await resp.Content.ReadAsStringAsync();
var showFiles = JsonConvert.DeserializeObject<List<string>>(showFilesResponse);
var files = showFiles
.Select(f =>
{
var fileName = Path.GetFileName(f);
return new FileMetaObject
{
DisplayDate = fileName.Substring(0, 10),
Date = DateTime.Parse(fileName.Substring(0, 10)),
FilePath = f,
Identifier =
fileName.Remove(fileName.LastIndexOf(".html", StringComparison.OrdinalIgnoreCase))
};
})
.ToList()
;
ctx?.WriteLine($"Checking {files.Count} html files");
var prog = ctx?.WriteProgressBar();
await files.AsyncForEachWithProgress(prog, async f =>
{
if (existingSetlistShows.ContainsKey(f.Identifier))
{
return;
}
var url = ShowPageUrl(src, f.FilePath);
var pageResp = await http.GetAsync(url);
var pageContents = await pageResp.Content.ReadAsStringAsync();
await ProcessPage(stats, artist, f, pageContents,
pageResp.Content.Headers.LastModified?.UtcDateTime ?? DateTime.UtcNow, ctx);
});
if (artist.features.tours)
{
await UpdateTourStartEndDates(artist);
}
ctx.WriteLine("Rebuilding shows and years");
// update shows
await RebuildShows(artist);
// update years
await RebuildYears(artist);
return stats;
}
public override Task<ImportStats> ImportSpecificShowDataForArtist(Artist artist, ArtistUpstreamSource src,
string showIdentifier, PerformContext ctx)
{
return Task.FromResult(new ImportStats());
}
private async Task PreloadData(Artist artist)
{
existingVenues = (await _venueService.AllIncludingUnusedForArtist(artist))
.GroupBy(venue => venue.upstream_identifier).ToDictionary(grp => grp.Key, grp => grp.First());
existingTours = (await _tourService.AllForArtist(artist))
.GroupBy(tour => tour.upstream_identifier).ToDictionary(grp => grp.Key, grp => grp.First());
existingSetlistShows = (await _setlistShowService.AllForArtist(artist))
.GroupBy(show => show.upstream_identifier).ToDictionary(grp => grp.Key, grp => grp.First());
existingSetlistSongs = (await _setlistSongService.AllForArtist(artist))
.GroupBy(song => song.upstream_identifier).ToDictionary(grp => grp.Key, grp => grp.First());
}
private async Task ProcessPage(ImportStats stats, Artist artist, FileMetaObject meta, string pageContents,
DateTime updated_at, PerformContext ctx)
{
var dbShow = existingSetlistShows.GetValue(meta.Identifier);
if (dbShow != null)
{
return;
}
ctx.WriteLine($"Processing: {meta.FilePath}");
var html = new HtmlDocument();
html.LoadHtml(pageContents);
var root = html.DocumentNode;
var ps = root.DescendantsWithClass("venue-name").ToList();
var bandName = ps[1].InnerText.CollapseSpacesAndTrim();
var venueName = ps[0].InnerText.CollapseSpacesAndTrim();
var venueCityOrCityState = root.DescendantsWithClass("venue-address").Single().InnerText
.CollapseSpacesAndTrim().TrimEnd(',');
var venueCountry = root.DescendantsWithClass("venue-country").Single().InnerText.CollapseSpacesAndTrim();
var tourName = ps.Count > 2 ? ps[2].InnerText.CollapseSpacesAndTrim() : "Not Part of a Tour";
var venueUpstreamId = "jerrygarcia.com_" + venueName;
Venue dbVenue = existingVenues.GetValue(venueUpstreamId);
if (dbVenue == null)
{
var sc = new VenueWithShowCount
{
artist_id = artist.id,
name = venueName,
location = venueCityOrCityState + ", " + venueCountry,
upstream_identifier = venueUpstreamId,
slug = Slugify(venueName),
updated_at = updated_at
};
dbVenue = await _venueService.Save(sc);
sc.id = dbVenue.id;
existingVenues[dbVenue.upstream_identifier] = sc;
stats.Created++;
}
var dbTour = existingTours.GetValue(tourName);
if (dbTour == null && artist.features.tours)
{
dbTour = await _tourService.Save(new Tour
{
artist_id = artist.id,
name = tourName,
slug = Slugify(tourName),
upstream_identifier = tourName,
updated_at = updated_at
});
existingTours[dbTour.upstream_identifier] = dbTour;
stats.Created++;
}
dbShow = await _setlistShowService.Save(new SetlistShow
{
artist_id = artist.id,
tour_id = dbTour?.id,
venue_id = dbVenue.id,
date = meta.Date,
upstream_identifier = meta.Identifier,
updated_at = updated_at
});
existingSetlistShows[dbShow.upstream_identifier] = dbShow;
stats.Created++;
var dbSongs = root.Descendants("ol")
.SelectMany(node => node.Descendants("li"))
.Select(node =>
{
var trackName = node.InnerText.Trim().TrimEnd('>', '*', ' ');
var slug = SlugifyTrack(trackName);
return new SetlistSong
{
artist_id = artist.id,
name = trackName,
slug = slug,
upstream_identifier = slug,
updated_at = updated_at
};
})
.GroupBy(s => s.upstream_identifier)
.Select(g => g.First())
.ToList()
;
ResetTrackSlugCounts();
var dbSongsToAdd = dbSongs.Where(song => !existingSetlistSongs.ContainsKey(song.upstream_identifier));
dbSongs = dbSongs.Where(song => existingSetlistSongs.ContainsKey(song.upstream_identifier))
.Select(song => existingSetlistSongs[song.upstream_identifier])
.ToList()
;
var added = await _setlistSongService.InsertAll(artist, dbSongsToAdd);
foreach (var s in added)
{
existingSetlistSongs[s.upstream_identifier] = s;
}
stats.Created += added.Count();
dbSongs.AddRange(added);
if (artist.features.tours &&
(dbTour.start_date == null
|| dbTour.end_date == null
|| dbShow.date < dbTour.start_date
|| dbShow.date > dbTour.end_date))
{
if (!tourToStartDate.ContainsKey(dbTour.upstream_identifier)
|| dbShow.date < tourToStartDate[dbTour.upstream_identifier])
{
tourToStartDate[dbTour.upstream_identifier] = dbShow.date;
}
if (!tourToEndDate.ContainsKey(dbTour.upstream_identifier)
|| dbShow.date > tourToEndDate[dbTour.upstream_identifier])
{
tourToEndDate[dbTour.upstream_identifier] = dbShow.date;
}
}
await _setlistShowService.UpdateSongPlays(dbShow, dbSongs);
}
private async Task UpdateTourStartEndDates(Artist artist)
{
await db.WithConnection(con => con.ExecuteAsync(@"
UPDATE
tours
SET
start_date = @startDate,
end_date = @endDate
WHERE
artist_id = @artistId
AND upstream_identifier = @upstream_identifier
", tourToStartDate.Keys.Select(tourUpstreamId =>
{
return new
{
startDate = tourToStartDate[tourUpstreamId],
endDate = tourToEndDate[tourUpstreamId],
artistId = artist.id,
upstream_identifier = tourUpstreamId
};
})));
tourToStartDate = new Dictionary<string, DateTime>();
tourToEndDate = new Dictionary<string, DateTime>();
}
private class FileMetaObject
{
public string DisplayDate { get; set; }
public DateTime Date { get; set; }
public string FilePath { get; set; }
public string Identifier { get; set; }
}
}
public static class HtmlExtensions
{
public static string CollapseSpacesAndTrim(this string str)
{
return Regex.Replace(str.Trim(), @"\s+", " ");
}
public static IEnumerable<HtmlNode> WhereHasClass(this IEnumerable<HtmlNode> nodes, string cls)
{
return nodes.Where(node => node.GetAttributeValue("class", "")
.Split(' ')
.Contains(cls));
}
public static IEnumerable<HtmlNode> DescendantsWithClass(this HtmlNode node, string cls)
{
return node.Descendants().WhereHasClass(cls);
}
}
}
| 37.152778 | 131 | 0.55529 | [
"MIT"
] | RelistenNet/RelistenApi | RelistenApi/Services/Importers/JerryGarciaComImporter.cs | 13,375 | C# |
using System;
using System.Reflection;
using NPC;
using Pipliz;
using Server.AI;
using Random = System.Random;
namespace Pandaros.Settlers
{
public static class ExtentionMethods
{
public static double NextDouble(this Random rng, double min, double max)
{
return rng.NextDouble() * (max - min) + min;
}
public static bool TakeItemFromInventory(this Players.Player player, ushort itemType)
{
var hasItem = false;
var invRef = Inventory.GetInventory(player);
if (invRef != null)
invRef.TryRemove(itemType);
return hasItem;
}
public static Vector3Int GetClosestPositionWithinY(this Vector3Int goalPosition, Vector3Int currentPosition,
int minMaxY)
{
var pos = AIManager.ClosestPosition(goalPosition, currentPosition);
if (pos == Vector3Int.invalidPos)
{
var y = -1;
var negY = minMaxY * -1;
while (pos == Vector3Int.invalidPos)
{
pos = AIManager.ClosestPosition(goalPosition.Add(0, y, 0), currentPosition);
if (y > 0)
{
y++;
if (y > minMaxY)
break;
}
else
{
y--;
if (y < negY)
y = 1;
}
}
}
return pos;
}
public static void Heal(this NPCBase nPC, float heal)
{
nPC.health += heal;
if (nPC.health > NPCBase.MaxHealth)
nPC.health = NPCBase.MaxHealth;
nPC.Update();
}
public static void Heal(this Players.Player pc, float heal)
{
pc.Health += heal;
if (pc.Health > pc.HealthMax)
pc.Health = pc.HealthMax;
pc.SendHealthPacket();
}
public static T Next<T>(this T src) where T : struct
{
if (!typeof(T).IsEnum)
throw new ArgumentException(string.Format("Argumnent {0} is not an Enum", typeof(T).FullName));
var Arr = (T[]) Enum.GetValues(src.GetType());
var j = Array.IndexOf(Arr, src) + 1;
return Arr.Length == j ? Arr[0] : Arr[j];
}
public static T CallAndReturn<T>(this object o, string methodName, params object[] args)
{
var retVal = default(T);
var mi = o.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (mi != null)
retVal = (T) mi.Invoke(o, args);
return retVal;
}
public static object Call(this object o, string methodName, params object[] args)
{
var mi = o.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (mi != null) return mi.Invoke(o, args);
return null;
}
public static rT GetFieldValue<rT, oT>(this object o, string fieldName)
{
return (rT) typeof(oT).GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(o);
}
public static void SetFieldValue<oT>(this object o, string fieldName, object fieldValue)
{
typeof(oT).GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).SetValue(o, fieldValue);
}
}
}
| 31.07438 | 137 | 0.513032 | [
"MIT"
] | pipliz/Pandaros.Settlers | Pandaros.Settlers/Pandaros.Settlers/ExtentionMethods.cs | 3,762 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the frauddetector-2019-11-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.FraudDetector.Model
{
/// <summary>
/// The outcome.
/// </summary>
public partial class Outcome
{
private string _arn;
private string _createdTime;
private string _description;
private string _lastUpdatedTime;
private string _name;
/// <summary>
/// Gets and sets the property Arn.
/// <para>
/// The outcome ARN.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=256)]
public string Arn
{
get { return this._arn; }
set { this._arn = value; }
}
// Check to see if Arn property is set
internal bool IsSetArn()
{
return this._arn != null;
}
/// <summary>
/// Gets and sets the property CreatedTime.
/// <para>
/// The timestamp when the outcome was created.
/// </para>
/// </summary>
public string CreatedTime
{
get { return this._createdTime; }
set { this._createdTime = value; }
}
// Check to see if CreatedTime property is set
internal bool IsSetCreatedTime()
{
return this._createdTime != null;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// The outcome description.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=128)]
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property LastUpdatedTime.
/// <para>
/// The timestamp when the outcome was last updated.
/// </para>
/// </summary>
public string LastUpdatedTime
{
get { return this._lastUpdatedTime; }
set { this._lastUpdatedTime = value; }
}
// Check to see if LastUpdatedTime property is set
internal bool IsSetLastUpdatedTime()
{
return this._lastUpdatedTime != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The outcome name.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=64)]
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
}
} | 27.235294 | 111 | 0.556156 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/FraudDetector/Generated/Model/Outcome.cs | 3,704 | C# |
using System.Collections.Generic;
using System.Text;
namespace LeetCode.P6;
public class Solution
{
private const int HorizontalPadding = 2;
// Runtime: 136 ms, (38.25%)
// Memory Usage: 37.8 MB, (86.98%)
public string Convert(string s, int numRows)
{
var horizontalLines = new List<char>[numRows];
for (var i = 0; i < numRows; i++)
{
horizontalLines[i] = new List<char>();
}
var horizontalIndex = 0;
var isGoingUp = false;
for (var i = 0; i < s.Length; i++)
{
horizontalLines[horizontalIndex].Add(s[i]);
if (isGoingUp && horizontalIndex <= 0)
{
isGoingUp = false;
}
horizontalIndex = isGoingUp
? horizontalIndex - 1
: horizontalIndex + 1;
if (horizontalIndex != 0 && horizontalIndex % numRows == 0)
{
isGoingUp = true;
horizontalIndex = numRows == 1
? 0
: horizontalIndex - HorizontalPadding;
}
}
var stringBuilder = new StringBuilder();
foreach (var horizontalLine in horizontalLines)
{
stringBuilder.Append(horizontalLine.ToArray());
}
return stringBuilder.ToString();
}
} | 24.375 | 71 | 0.514286 | [
"MIT"
] | ch200c/leetcode-cs | LeetCode/P6/Solution.cs | 1,367 | C# |
using System;
using TreniniDotNet.Common.Data;
using TreniniDotNet.Infrastructure.Dapper;
using TreniniDotNet.Infrastructure.Database.Testing;
namespace TreniniDotNet.Infrastructure.Persistence.Repositories
{
public abstract class DapperRepositoryUnitTests<TRepository>
{
protected TRepository Repository { get; }
protected IUnitOfWork UnitOfWork { get; }
protected DatabaseTestHelpers Database { get; }
protected DapperRepositoryUnitTests(Func<IUnitOfWork, TRepository> builder)
{
var config = new RepositoryDatabaseConfig();
Database = new DatabaseTestHelpers(config.ConnectionProvider);
UnitOfWork = new DapperUnitOfWork(config.ConnectionProvider);
Repository = builder(UnitOfWork);
}
}
} | 33.458333 | 83 | 0.722291 | [
"MIT"
] | CarloMicieli/TreniniDotNet | Tests/Infrastructure.UnitTests/Persistence/Repositories/DapperRepositoryUnitTests.cs | 803 | C# |
namespace BroachingAnalysis
{
partial class frmOptions
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.cbPartNo = new System.Windows.Forms.ComboBox();
this.btnZero = new System.Windows.Forms.Button();
this.llblOptionsAdv = new System.Windows.Forms.LinkLabel();
this.btnApply = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.gbOptions = new System.Windows.Forms.GroupBox();
this.gbAdvanced = new System.Windows.Forms.GroupBox();
this.btnAdd = new System.Windows.Forms.Button();
this.btnDelete = new System.Windows.Forms.Button();
this.cbPartSelect = new System.Windows.Forms.ComboBox();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.txtPartno = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.txtSteel = new System.Windows.Forms.TextBox();
this.txtTolerance = new System.Windows.Forms.TextBox();
this.txtSlots = new System.Windows.Forms.TextBox();
this.lblCount = new System.Windows.Forms.Label();
this.txtRingcount = new System.Windows.Forms.TextBox();
this.btnUnzero = new System.Windows.Forms.Button();
this.gbOptions.SuspendLayout();
this.gbAdvanced.SuspendLayout();
this.SuspendLayout();
//
// cbPartNo
//
this.cbPartNo.FormattingEnabled = true;
this.cbPartNo.Location = new System.Drawing.Point(6, 19);
this.cbPartNo.Name = "cbPartNo";
this.cbPartNo.Size = new System.Drawing.Size(121, 21);
this.cbPartNo.TabIndex = 0;
//
// btnZero
//
this.btnZero.Location = new System.Drawing.Point(23, 58);
this.btnZero.Name = "btnZero";
this.btnZero.Size = new System.Drawing.Size(75, 23);
this.btnZero.TabIndex = 1;
this.btnZero.Text = "Zero Value";
this.btnZero.UseVisualStyleBackColor = true;
this.btnZero.Click += new System.EventHandler(this.btnZero_Click);
//
// llblOptionsAdv
//
this.llblOptionsAdv.AutoSize = true;
this.llblOptionsAdv.Location = new System.Drawing.Point(12, 282);
this.llblOptionsAdv.Name = "llblOptionsAdv";
this.llblOptionsAdv.Size = new System.Drawing.Size(107, 13);
this.llblOptionsAdv.TabIndex = 1;
this.llblOptionsAdv.TabStop = true;
this.llblOptionsAdv.Text = "Advanced Options ...";
this.llblOptionsAdv.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.llblOptionsAdv_LinkClicked);
//
// btnApply
//
this.btnApply.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnApply.Location = new System.Drawing.Point(219, 273);
this.btnApply.Name = "btnApply";
this.btnApply.Size = new System.Drawing.Size(75, 23);
this.btnApply.TabIndex = 2;
this.btnApply.Text = "Apply";
this.btnApply.UseVisualStyleBackColor = true;
this.btnApply.Click += new System.EventHandler(this.btnApply_Click);
//
// btnCancel
//
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.Location = new System.Drawing.Point(300, 273);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 23);
this.btnCancel.TabIndex = 3;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// gbOptions
//
this.gbOptions.Controls.Add(this.cbPartNo);
this.gbOptions.Controls.Add(this.btnZero);
this.gbOptions.Location = new System.Drawing.Point(12, 12);
this.gbOptions.Name = "gbOptions";
this.gbOptions.Size = new System.Drawing.Size(136, 255);
this.gbOptions.TabIndex = 0;
this.gbOptions.TabStop = false;
this.gbOptions.Text = "Options";
//
// gbAdvanced
//
this.gbAdvanced.Controls.Add(this.btnAdd);
this.gbAdvanced.Controls.Add(this.btnDelete);
this.gbAdvanced.Controls.Add(this.cbPartSelect);
this.gbAdvanced.Controls.Add(this.label5);
this.gbAdvanced.Controls.Add(this.label4);
this.gbAdvanced.Controls.Add(this.txtPartno);
this.gbAdvanced.Controls.Add(this.label3);
this.gbAdvanced.Controls.Add(this.label2);
this.gbAdvanced.Controls.Add(this.label1);
this.gbAdvanced.Controls.Add(this.txtSteel);
this.gbAdvanced.Controls.Add(this.txtTolerance);
this.gbAdvanced.Controls.Add(this.txtSlots);
this.gbAdvanced.Controls.Add(this.lblCount);
this.gbAdvanced.Controls.Add(this.txtRingcount);
this.gbAdvanced.Controls.Add(this.btnUnzero);
this.gbAdvanced.Location = new System.Drawing.Point(154, 12);
this.gbAdvanced.Name = "gbAdvanced";
this.gbAdvanced.Size = new System.Drawing.Size(227, 255);
this.gbAdvanced.TabIndex = 4;
this.gbAdvanced.TabStop = false;
this.gbAdvanced.Text = "Advanced";
//
// btnAdd
//
this.btnAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnAdd.Location = new System.Drawing.Point(65, 217);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(75, 23);
this.btnAdd.TabIndex = 14;
this.btnAdd.Text = "Add";
this.btnAdd.UseVisualStyleBackColor = true;
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// btnDelete
//
this.btnDelete.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnDelete.Location = new System.Drawing.Point(146, 217);
this.btnDelete.Name = "btnDelete";
this.btnDelete.Size = new System.Drawing.Size(75, 23);
this.btnDelete.TabIndex = 15;
this.btnDelete.Text = "Delete";
this.btnDelete.UseVisualStyleBackColor = true;
this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
//
// cbPartSelect
//
this.cbPartSelect.FormattingEnabled = true;
this.cbPartSelect.Location = new System.Drawing.Point(75, 84);
this.cbPartSelect.Name = "cbPartSelect";
this.cbPartSelect.Size = new System.Drawing.Size(121, 21);
this.cbPartSelect.TabIndex = 5;
this.cbPartSelect.SelectedIndexChanged += new System.EventHandler(this.cbPartSelect_SelectedIndexChanged);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(6, 87);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(43, 13);
this.label5.TabIndex = 4;
this.label5.Text = "Select..";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(5, 113);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(43, 13);
this.label4.TabIndex = 6;
this.label4.Text = "Part No";
//
// txtPartno
//
this.txtPartno.Location = new System.Drawing.Point(75, 113);
this.txtPartno.Name = "txtPartno";
this.txtPartno.Size = new System.Drawing.Size(100, 20);
this.txtPartno.TabIndex = 7;
this.txtPartno.TextChanged += new System.EventHandler(this.txtPart_TextChanged);
this.txtPartno.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtPartno_KeyPress);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(6, 191);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(36, 13);
this.label3.TabIndex = 12;
this.label3.Text = "Steels";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(6, 165);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(55, 13);
this.label2.TabIndex = 10;
this.label2.Text = "Tolerance";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 139);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(30, 13);
this.label1.TabIndex = 8;
this.label1.Text = "Slots";
//
// txtSteel
//
this.txtSteel.Location = new System.Drawing.Point(76, 191);
this.txtSteel.Name = "txtSteel";
this.txtSteel.Size = new System.Drawing.Size(100, 20);
this.txtSteel.TabIndex = 13;
this.txtSteel.TextChanged += new System.EventHandler(this.txtPart_TextChanged);
this.txtSteel.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtSteel_KeyPress);
//
// txtTolerance
//
this.txtTolerance.Location = new System.Drawing.Point(76, 165);
this.txtTolerance.Name = "txtTolerance";
this.txtTolerance.Size = new System.Drawing.Size(100, 20);
this.txtTolerance.TabIndex = 11;
this.txtTolerance.TextChanged += new System.EventHandler(this.txtPart_TextChanged);
this.txtTolerance.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtTolerance_KeyPress);
//
// txtSlots
//
this.txtSlots.Location = new System.Drawing.Point(76, 139);
this.txtSlots.Name = "txtSlots";
this.txtSlots.Size = new System.Drawing.Size(100, 20);
this.txtSlots.TabIndex = 9;
this.txtSlots.TextChanged += new System.EventHandler(this.txtPart_TextChanged);
this.txtSlots.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtSlots_KeyPress);
//
// lblCount
//
this.lblCount.AutoSize = true;
this.lblCount.Location = new System.Drawing.Point(6, 22);
this.lblCount.Name = "lblCount";
this.lblCount.Size = new System.Drawing.Size(63, 13);
this.lblCount.TabIndex = 0;
this.lblCount.Text = "Ring Count:";
//
// txtRingcount
//
this.txtRingcount.Location = new System.Drawing.Point(75, 19);
this.txtRingcount.Name = "txtRingcount";
this.txtRingcount.Size = new System.Drawing.Size(100, 20);
this.txtRingcount.TabIndex = 1;
this.txtRingcount.Text = "944000";
this.txtRingcount.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtRingcount_KeyPress);
//
// btnUnzero
//
this.btnUnzero.Location = new System.Drawing.Point(6, 45);
this.btnUnzero.Name = "btnUnzero";
this.btnUnzero.Size = new System.Drawing.Size(75, 23);
this.btnUnzero.TabIndex = 3;
this.btnUnzero.Text = "Un-Zero";
this.btnUnzero.UseVisualStyleBackColor = true;
this.btnUnzero.Click += new System.EventHandler(this.btnUnzero_Click);
//
// frmOptions
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(394, 312);
this.Controls.Add(this.gbAdvanced);
this.Controls.Add(this.gbOptions);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnApply);
this.Controls.Add(this.llblOptionsAdv);
this.Name = "frmOptions";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Options";
this.Load += new System.EventHandler(this.frmOptions_Load);
this.gbOptions.ResumeLayout(false);
this.gbAdvanced.ResumeLayout(false);
this.gbAdvanced.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ComboBox cbPartNo;
private System.Windows.Forms.Button btnZero;
private System.Windows.Forms.LinkLabel llblOptionsAdv;
private System.Windows.Forms.Button btnApply;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.GroupBox gbOptions;
private System.Windows.Forms.GroupBox gbAdvanced;
private System.Windows.Forms.Label lblCount;
private System.Windows.Forms.TextBox txtRingcount;
private System.Windows.Forms.Button btnUnzero;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtPartno;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtSteel;
private System.Windows.Forms.TextBox txtTolerance;
private System.Windows.Forms.TextBox txtSlots;
private System.Windows.Forms.ComboBox cbPartSelect;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.Button btnDelete;
}
} | 47.815152 | 160 | 0.591292 | [
"Unlicense"
] | addshore/BroachingAnalysis | BroachingAnalysis/frmOptions.Designer.cs | 15,781 | C# |
/*
* API Doctor
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the ""Software""), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace ApiDoctor.Validation.OData
{
using Utility;
using System.Xml.Serialization;
/// <summary>
/// Function in OData is not allowed to modify data
/// or have side effects (must be idempotent). A
/// function must return data back to the caller (ReturnType).
/// </summary>
[XmlRoot("Function", Namespace = ODataParser.EdmNamespace)]
public class Function : ActionOrFunctionBase
{
public Function() : base()
{
}
[XmlAttribute("IsComposable"), MergePolicy(MergePolicy.PreferLesserValue)]
public bool IsComposable { get; set; }
[XmlIgnore]
public bool IsComposableSpecified => this.IsComposable;
}
}
| 38 | 87 | 0.71 | [
"MIT"
] | BarryShehadeh/apidoctor | ApiDoctor.Validation/OData/Function.cs | 1,902 | C# |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Xml;
using EnvDTE;
using Microsoft.Build.Execution;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
using IServiceProvider = System.IServiceProvider;
using MSBuild = Microsoft.Build.Evaluation;
using MSBuildConstruction = Microsoft.Build.Construction;
using MSBuildExecution = Microsoft.Build.Execution;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
namespace Microsoft.VisualStudioTools.Project {
/// <summary>
/// Manages the persistent state of the project (References, options, files, etc.) and deals with user interaction via a GUI in the form a hierarchy.
/// </summary>
internal abstract partial class ProjectNode : HierarchyNode,
IVsUIHierarchy,
IVsPersistHierarchyItem2,
IVsHierarchyDeleteHandler,
IVsHierarchyDeleteHandler2,
IVsHierarchyDropDataTarget,
IVsHierarchyDropDataSource,
IVsHierarchyDropDataSource2,
IVsGetCfgProvider,
IVsProject3,
IVsAggregatableProject,
IVsProjectFlavorCfgProvider,
IPersistFileFormat,
IVsBuildPropertyStorage,
IVsComponentUser,
IVsDependencyProvider,
IVsSccProject2,
IBuildDependencyUpdate,
IVsProjectSpecialFiles,
IVsProjectBuildSystem,
IOleCommandTarget {
#region nested types
#if DEV14_OR_LATER
[Obsolete("Use ImageMonikers instead")]
#endif
public enum ImageName {
OfflineWebApp = 0,
WebReferencesFolder = 1,
OpenReferenceFolder = 2,
ReferenceFolder = 3,
Reference = 4,
SDLWebReference = 5,
DISCOWebReference = 6,
Folder = 7,
OpenFolder = 8,
ExcludedFolder = 9,
OpenExcludedFolder = 10,
ExcludedFile = 11,
DependentFile = 12,
MissingFile = 13,
WindowsForm = 14,
WindowsUserControl = 15,
WindowsComponent = 16,
XMLSchema = 17,
XMLFile = 18,
WebForm = 19,
WebService = 20,
WebUserControl = 21,
WebCustomUserControl = 22,
ASPPage = 23,
GlobalApplicationClass = 24,
WebConfig = 25,
HTMLPage = 26,
StyleSheet = 27,
ScriptFile = 28,
TextFile = 29,
SettingsFile = 30,
Resources = 31,
Bitmap = 32,
Icon = 33,
Image = 34,
ImageMap = 35,
XWorld = 36,
Audio = 37,
Video = 38,
CAB = 39,
JAR = 40,
DataEnvironment = 41,
PreviewFile = 42,
DanglingReference = 43,
XSLTFile = 44,
Cursor = 45,
AppDesignerFolder = 46,
Data = 47,
Application = 48,
DataSet = 49,
PFX = 50,
SNK = 51,
ImageLast = 51
}
/// <summary>
/// Flags for specifying which events to stop triggering.
/// </summary>
[Flags]
internal enum EventTriggering {
TriggerAll = 0,
DoNotTriggerHierarchyEvents = 1,
DoNotTriggerTrackerEvents = 2,
DoNotTriggerTrackerQueryEvents = 4
}
#endregion
#region constants
/// <summary>
/// The user file extension.
/// </summary>
internal const string PerUserFileExtension = ".user";
#endregion
#region fields
/// <summary>
/// List of output groups names and their associated target
/// </summary>
private static KeyValuePair<string, string>[] outputGroupNames =
{ // Name ItemGroup (MSBuild)
new KeyValuePair<string, string>("Built", "BuiltProjectOutputGroup"),
new KeyValuePair<string, string>("ContentFiles", "ContentFilesProjectOutputGroup"),
new KeyValuePair<string, string>("LocalizedResourceDlls", "SatelliteDllsProjectOutputGroup"),
new KeyValuePair<string, string>("Documentation", "DocumentationProjectOutputGroup"),
new KeyValuePair<string, string>("Symbols", "DebugSymbolsProjectOutputGroup"),
new KeyValuePair<string, string>("SourceFiles", "SourceFilesProjectOutputGroup"),
new KeyValuePair<string, string>("XmlSerializer", "SGenFilesOutputGroup"),
};
private EventSinkCollection _hierarchyEventSinks = new EventSinkCollection();
/// <summary>A project will only try to build if it can obtain a lock on this object</summary>
private volatile static object BuildLock = new object();
/// <summary>Maps integer ids to project item instances</summary>
private HierarchyIdMap itemIdMap = new HierarchyIdMap();
/// <summary>A service provider call back object provided by the IDE hosting the project manager</summary>
private IServiceProvider site;
private TrackDocumentsHelper tracker;
/// <summary>
/// MSBuild engine we are going to use
/// </summary>
private MSBuild.ProjectCollection buildEngine;
private Microsoft.Build.Utilities.Logger buildLogger;
private bool useProvidedLogger;
private MSBuild.Project buildProject;
private MSBuildExecution.ProjectInstance currentConfig;
private ConfigProvider configProvider;
private TaskProvider taskProvider;
private string filename;
private Microsoft.VisualStudio.Shell.Url baseUri;
private string projectHome;
/// <summary>
/// Used by OAProject to override the dirty state.
/// </summary>
internal bool isDirty;
private bool projectOpened;
private string errorString;
private string warningString;
private ImageHandler imageHandler;
private Guid projectIdGuid;
private bool isClosed, isClosing;
private EventTriggering eventTriggeringFlag = EventTriggering.TriggerAll;
private bool canFileNodesHaveChilds;
private bool isProjectEventsListener = true;
/// <summary>
/// The build dependency list passed to IVsDependencyProvider::EnumDependencies
/// </summary>
private List<IVsBuildDependency> buildDependencyList = new List<IVsBuildDependency>();
/// <summary>
/// Defines if Project System supports Project Designer
/// </summary>
private bool supportsProjectDesigner;
private bool showProjectInSolutionPage = true;
private bool buildInProcess;
private string sccProjectName;
private string sccLocalPath;
private string sccAuxPath;
private string sccProvider;
/// <summary>
/// Flag for controling how many times we register with the Scc manager.
/// </summary>
private bool isRegisteredWithScc;
/// <summary>
/// Flag for controling query edit should communicate with the scc manager.
/// </summary>
private bool disableQueryEdit;
/// <summary>
/// Control if command with potential destructive behavior such as delete should
/// be enabled for nodes of this project.
/// </summary>
private bool canProjectDeleteItems;
/// <summary>
/// Member to store output base relative path. Used by OutputBaseRelativePath property
/// </summary>
private string outputBaseRelativePath = "bin";
/// <summary>
/// Used for flavoring to hold the XML fragments
/// </summary>
private XmlDocument xmlFragments;
/// <summary>
/// Used to map types to CATID. This provide a generic way for us to do this
/// and make it simpler for a project to provide it's CATIDs for the different type of objects
/// for which it wants to support extensibility. This also enables us to have multiple
/// type mapping to the same CATID if we choose to.
/// </summary>
private Dictionary<Type, Guid> catidMapping;
/// <summary>
/// Mapping from item names to their hierarchy nodes for all disk-based nodes.
/// </summary>
protected readonly Dictionary<string, HierarchyNode> _diskNodes = new Dictionary<string, HierarchyNode>(StringComparer.OrdinalIgnoreCase);
// Has the object been disposed.
private bool isDisposed;
private IVsHierarchy parentHierarchy;
private int parentHierarchyItemId;
private List<HierarchyNode> itemsDraggedOrCutOrCopied;
/// <summary>
/// Folder node in the process of being created. First the hierarchy node
/// is added, then the label is edited, and when that completes/cancels
/// the folder gets created.
/// </summary>
private FolderNode _folderBeingCreated;
private readonly ExtensibilityEventsDispatcher extensibilityEventsDispatcher;
#endregion
#region abstract properties
/// <summary>
/// This Guid must match the Guid you registered under
/// HKLM\Software\Microsoft\VisualStudio\%version%\Projects.
/// Among other things, the Project framework uses this
/// guid to find your project and item templates.
/// </summary>
public abstract Guid ProjectGuid {
get;
}
/// <summary>
/// Returns a caption for VSHPROPID_TypeName.
/// </summary>
/// <returns></returns>
public abstract string ProjectType {
get;
}
internal abstract string IssueTrackerUrl {
get;
}
#endregion
#region virtual properties
/// <summary>
/// Indicates whether or not the project system supports Show All Files.
///
/// Subclasses will need to return true here, and will need to handle calls
/// </summary>
public virtual bool CanShowAllFiles {
get {
return false;
}
}
/// <summary>
/// Indicates whether or not the project is currently in the mode where its showing all files.
/// </summary>
public virtual bool IsShowingAllFiles {
get {
return false;
}
}
/// <summary>
/// Represents the command guid for the project system. This enables
/// using CommonConstants.cmdid* commands.
///
/// By default these commands are disabled if this isn't overridden
/// with the packages command guid.
/// </summary>
public virtual Guid SharedCommandGuid {
get {
return CommonConstants.NoSharedCommandsGuid;
}
}
/// <summary>
/// This is the project instance guid that is peristed in the project file
/// </summary>
[System.ComponentModel.BrowsableAttribute(false)]
public virtual Guid ProjectIDGuid {
get {
return this.projectIdGuid;
}
set {
if (this.projectIdGuid != value) {
this.projectIdGuid = value;
if (this.buildProject != null) {
this.SetProjectProperty("ProjectGuid", this.projectIdGuid.ToString("B"));
}
}
}
}
public override bool CanAddFiles {
get {
return true;
}
}
#endregion
#region properties
internal bool IsProjectOpened {
get {
return projectOpened;
}
}
internal ExtensibilityEventsDispatcher ExtensibilityEventsDispatcher {
get {
return extensibilityEventsDispatcher;
}
}
/// <summary>
/// Gets the folder node which is currently being added to the project via
/// Solution Explorer.
/// </summary>
internal FolderNode FolderBeingCreated {
get {
return _folderBeingCreated;
}
set {
_folderBeingCreated = value;
}
}
internal IList<HierarchyNode> ItemsDraggedOrCutOrCopied {
get {
return this.itemsDraggedOrCutOrCopied;
}
}
public MSBuildExecution.ProjectInstance CurrentConfig {
get {
return currentConfig;
}
}
public Dictionary<string, HierarchyNode> DiskNodes {
get {
return _diskNodes;
}
}
#region overridden properties
public override bool CanOpenCommandPrompt {
get {
return true;
}
}
internal override string FullPathToChildren {
get {
return ProjectHome;
}
}
public override int MenuCommandId {
get {
return VsMenus.IDM_VS_CTXT_PROJNODE;
}
}
public override string Url {
get {
return this.GetMkDocument();
}
}
public override string Caption {
get {
var project = this.buildProject;
if (project == null) {
// Project is not available, which probably means we are
// in the process of closing
return string.Empty;
}
// Use file name
string caption = project.FullPath;
if (String.IsNullOrEmpty(caption)) {
if (project.GetProperty(ProjectFileConstants.Name) != null) {
caption = project.GetProperty(ProjectFileConstants.Name).EvaluatedValue;
if (caption == null || caption.Length == 0) {
caption = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
}
}
} else {
caption = Path.GetFileNameWithoutExtension(caption);
}
return caption;
}
}
public override Guid ItemTypeGuid {
get {
return this.ProjectGuid;
}
}
#pragma warning disable 0618, 0672
// Project subclasses decide whether or not to support using image
// monikers, and so we need to keep the ImageIndex overrides in case
// they choose not to.
public override int ImageIndex {
get {
return (int)ProjectNode.ImageName.Application;
}
}
#pragma warning restore 0618, 0672
#endregion
#region virtual properties
public virtual string ErrorString {
get {
if (this.errorString == null) {
this.errorString = SR.GetString(SR.Error);
}
return this.errorString;
}
}
public virtual string WarningString {
get {
if (this.warningString == null) {
this.warningString = SR.GetString(SR.Warning);
}
return this.warningString;
}
}
/// <summary>
/// Override this property to specify when the project file is dirty.
/// </summary>
protected virtual bool IsProjectFileDirty {
get {
string document = this.GetMkDocument();
if (String.IsNullOrEmpty(document)) {
return this.isDirty;
}
return (this.isDirty || !File.Exists(document));
}
}
/// <summary>
/// True if the project uses the Project Designer Editor instead of the property page frame to edit project properties.
/// </summary>
protected bool SupportsProjectDesigner {
get {
return this.supportsProjectDesigner;
}
set {
this.supportsProjectDesigner = value;
}
}
protected virtual Guid ProjectDesignerEditor {
get {
return VSConstants.GUID_ProjectDesignerEditor;
}
}
/// <summary>
/// Defines the flag that supports the VSHPROPID.ShowProjInSolutionPage
/// </summary>
protected virtual bool ShowProjectInSolutionPage {
get {
return this.showProjectInSolutionPage;
}
set {
this.showProjectInSolutionPage = value;
}
}
/// <summary>
/// A space separated list of the project's capabilities.
/// </summary>
/// <remarks>
/// These may be used by extensions to check whether they support this
/// project type. In general, this should only contain fundamental
/// properties of the project, such as the language name.
/// </remarks>
protected virtual string ProjectCapabilities {
get {
return null;
}
}
#endregion
/// <summary>
/// Gets or sets the ability of a project filenode to have child nodes (sub items).
/// Example would be C#/VB forms having resx and designer files.
/// </summary>
protected internal bool CanFileNodesHaveChilds {
get {
return canFileNodesHaveChilds;
}
set {
canFileNodesHaveChilds = value;
}
}
/// <summary>
/// Gets a service provider object provided by the IDE hosting the project
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
public IServiceProvider Site {
get {
return this.site;
}
}
/// <summary>
/// Gets an ImageHandler for the project node.
/// </summary>
#if DEV14_OR_LATER
[Obsolete("Use ImageMonikers instead")]
#endif
public ImageHandler ImageHandler {
get {
if (null == imageHandler) {
imageHandler = new ImageHandler(ProjectIconsImageStripStream);
}
return imageHandler;
}
}
protected abstract Stream ProjectIconsImageStripStream {
get;
}
/// <summary>
/// Gets the path to the root folder of the project.
/// </summary>
public string ProjectHome {
get {
if (projectHome == null) {
projectHome = CommonUtils.GetAbsoluteDirectoryPath(
this.ProjectFolder,
this.GetProjectProperty(CommonConstants.ProjectHome, resetCache: false));
}
Debug.Assert(projectHome != null, "ProjectHome should not be null");
return projectHome;
}
}
/// <summary>
/// Gets the path to the folder containing the project.
/// </summary>
public string ProjectFolder {
get {
return Path.GetDirectoryName(this.filename);
}
}
/// <summary>
/// Gets or sets the project filename.
/// </summary>
public string ProjectFile {
get {
return Path.GetFileName(this.filename);
}
set {
this.SetEditLabel(value);
}
}
/// <summary>
/// Gets the Base Uniform Resource Identifier (URI).
/// </summary>
public Microsoft.VisualStudio.Shell.Url BaseURI {
get {
if (baseUri == null && this.buildProject != null) {
string path = CommonUtils.NormalizeDirectoryPath(Path.GetDirectoryName(this.buildProject.FullPath));
baseUri = new Url(path);
}
Debug.Assert(baseUri != null, "Base URL should not be null. Did you call BaseURI before loading the project?");
return baseUri;
}
}
protected void BuildProjectLocationChanged() {
baseUri = null;
projectHome = null;
}
/// <summary>
/// Gets whether or not the project is closed.
/// </summary>
public bool IsClosed {
get {
return this.isClosed;
}
}
/// <summary>
/// Gets whether or not the project has begun closing.
/// </summary>
public bool IsClosing {
get {
return this.isClosing;
}
}
/// <summary>
/// Gets whether or not the project is being built.
/// </summary>
public bool BuildInProgress {
get {
return buildInProcess;
}
}
/// <summary>
/// Gets or set the relative path to the folder containing the project ouput.
/// </summary>
public virtual string OutputBaseRelativePath {
get {
return this.outputBaseRelativePath;
}
set {
if (Path.IsPathRooted(value)) {
// TODO: Maybe bring the exception back instead of automatically fixing this?
this.outputBaseRelativePath = CommonUtils.GetRelativeDirectoryPath(ProjectHome, value);
}
this.outputBaseRelativePath = value;
}
}
/// <summary>
/// Gets a collection of integer ids that maps to project item instances
/// </summary>
internal HierarchyIdMap ItemIdMap {
get {
return this.itemIdMap;
}
}
/// <summary>
/// Get the helper object that track document changes.
/// </summary>
internal TrackDocumentsHelper Tracker {
get {
return this.tracker;
}
}
/// <summary>
/// Gets or sets the build logger.
/// </summary>
protected Microsoft.Build.Utilities.Logger BuildLogger {
get {
return this.buildLogger;
}
set {
this.buildLogger = value;
this.useProvidedLogger = value != null;
}
}
/// <summary>
/// Gets the taskprovider.
/// </summary>
protected TaskProvider TaskProvider {
get {
return this.taskProvider;
}
}
/// <summary>
/// Gets the project file name.
/// </summary>
protected string FileName {
get {
return this.filename;
}
}
/// <summary>
/// Gets the configuration provider.
/// </summary>
protected internal ConfigProvider ConfigProvider {
get {
if (this.configProvider == null) {
this.configProvider = CreateConfigProvider();
}
return this.configProvider;
}
}
/// <summary>
/// Gets or set whether items can be deleted for this project.
/// Enabling this feature can have the potential destructive behavior such as deleting files from disk.
/// </summary>
protected internal bool CanProjectDeleteItems {
get {
return canProjectDeleteItems;
}
set {
canProjectDeleteItems = value;
}
}
/// <summary>
/// Gets or sets event triggering flags.
/// </summary>
internal EventTriggering EventTriggeringFlag {
get {
return this.eventTriggeringFlag;
}
set {
this.eventTriggeringFlag = value;
}
}
/// <summary>
/// Defines the build project that has loaded the project file.
/// </summary>
protected internal MSBuild.Project BuildProject {
get {
return this.buildProject;
}
set {
SetBuildProject(value);
}
}
/// <summary>
/// Defines the build engine that is used to build the project file.
/// </summary>
internal MSBuild.ProjectCollection BuildEngine {
get {
return this.buildEngine;
}
set {
this.buildEngine = value;
}
}
#endregion
#region ctor
protected ProjectNode(IServiceProvider serviceProvider) {
this.extensibilityEventsDispatcher = new ExtensibilityEventsDispatcher(this);
this.Initialize();
this.site = serviceProvider;
taskProvider = new TaskProvider(this.site);
}
#endregion
#region overridden methods
protected internal override void DeleteFromStorage(string path) {
if (File.Exists(path)) {
File.Delete(path);
}
base.DeleteFromStorage(path);
}
/// <summary>
/// Sets the properties for the project node.
/// </summary>
/// <param name="propid">Identifier of the hierarchy property. For a list of propid values, <see cref="__VSHPROPID"/> </param>
/// <param name="value">The value to set. </param>
/// <returns>A success or failure value.</returns>
public override int SetProperty(int propid, object value) {
__VSHPROPID id = (__VSHPROPID)propid;
switch (id) {
case __VSHPROPID.VSHPROPID_ParentHierarchy:
parentHierarchy = (IVsHierarchy)value;
break;
case __VSHPROPID.VSHPROPID_ParentHierarchyItemid:
parentHierarchyItemId = (int)value;
break;
case __VSHPROPID.VSHPROPID_ShowProjInSolutionPage:
this.ShowProjectInSolutionPage = (bool)value;
return VSConstants.S_OK;
}
return base.SetProperty(propid, value);
}
/// <summary>
/// Renames the project node.
/// </summary>
/// <param name="label">The new name</param>
/// <returns>A success or failure value.</returns>
public override int SetEditLabel(string label) {
// Validate the filename.
if (Utilities.IsFileNameInvalid(label)) {
throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, label));
} else if (this.ProjectFolder.Length + label.Length + 1 > NativeMethods.MAX_PATH) {
throw new InvalidOperationException(SR.GetString(SR.PathTooLong, label));
}
// TODO: Take file extension into account?
string fileName = Path.GetFileNameWithoutExtension(label);
// Nothing to do if the name is the same
string oldFileName = Path.GetFileNameWithoutExtension(this.Url);
if (String.Equals(oldFileName, label, StringComparison.Ordinal)) {
return VSConstants.S_FALSE;
}
// Now check whether the original file is still there. It could have been renamed.
if (!File.Exists(this.Url)) {
throw new InvalidOperationException(SR.GetString(SR.FileOrFolderCannotBeFound, ProjectFile));
}
// Get the full file name and then rename the project file.
string newFile = Path.Combine(this.ProjectFolder, label);
string extension = Path.GetExtension(this.Url);
// Make sure it has the correct extension
if (!String.Equals(Path.GetExtension(newFile), extension, StringComparison.OrdinalIgnoreCase)) {
newFile += extension;
}
this.RenameProjectFile(newFile);
return VSConstants.S_OK;
}
/// <summary>
/// Gets the automation object for the project node.
/// </summary>
/// <returns>An instance of an EnvDTE.Project implementation object representing the automation object for the project.</returns>
public override object GetAutomationObject() {
return new Automation.OAProject(this);
}
/// <summary>
/// Gets the properties of the project node.
/// </summary>
/// <param name="propId">The __VSHPROPID of the property.</param>
/// <returns>A property dependent value. See: <see cref="__VSHPROPID"/> for details.</returns>
public override object GetProperty(int propId) {
switch ((__VSHPROPID)propId) {
case (__VSHPROPID)__VSHPROPID4.VSHPROPID_TargetFrameworkMoniker:
// really only here for testing so WAP projects load correctly...
// But this also impacts the toolbox by filtering what available items there are.
return ".NETFramework,Version=v4.0,Profile=Client";
case __VSHPROPID.VSHPROPID_ConfigurationProvider:
return this.ConfigProvider;
case __VSHPROPID.VSHPROPID_ProjectName:
return this.Caption;
case __VSHPROPID.VSHPROPID_ProjectDir:
return this.ProjectFolder;
case __VSHPROPID.VSHPROPID_TypeName:
return this.ProjectType;
case __VSHPROPID.VSHPROPID_ShowProjInSolutionPage:
return this.ShowProjectInSolutionPage;
case __VSHPROPID.VSHPROPID_ExpandByDefault:
return true;
case __VSHPROPID.VSHPROPID_DefaultEnableDeployProjectCfg:
return true;
case __VSHPROPID.VSHPROPID_DefaultEnableBuildProjectCfg:
return true;
// Use the same icon as if the folder was closed
case __VSHPROPID.VSHPROPID_OpenFolderIconIndex:
return GetProperty((int)__VSHPROPID.VSHPROPID_IconIndex);
case __VSHPROPID.VSHPROPID_ParentHierarchyItemid:
if (parentHierarchy != null) {
return (IntPtr)parentHierarchyItemId; // VS requires VT_I4 | VT_INT_PTR
}
break;
case __VSHPROPID.VSHPROPID_ParentHierarchy:
return parentHierarchy;
}
switch ((__VSHPROPID2)propId) {
case __VSHPROPID2.VSHPROPID_SupportsProjectDesigner:
return this.SupportsProjectDesigner;
case __VSHPROPID2.VSHPROPID_PropertyPagesCLSIDList:
return Utilities.CreateSemicolonDelimitedListOfStringFromGuids(this.GetConfigurationIndependentPropertyPages());
case __VSHPROPID2.VSHPROPID_CfgPropertyPagesCLSIDList:
return Utilities.CreateSemicolonDelimitedListOfStringFromGuids(this.GetConfigurationDependentPropertyPages());
case __VSHPROPID2.VSHPROPID_PriorityPropertyPagesCLSIDList:
return Utilities.CreateSemicolonDelimitedListOfStringFromGuids(this.GetPriorityProjectDesignerPages());
case __VSHPROPID2.VSHPROPID_Container:
return true;
default:
break;
}
#if DEV11_OR_LATER
switch ((__VSHPROPID5)propId) {
case __VSHPROPID5.VSHPROPID_ProjectCapabilities:
var caps = ProjectCapabilities;
if (!string.IsNullOrEmpty(caps)) {
return caps;
}
break;
}
#endif
return base.GetProperty(propId);
}
/// <summary>
/// Gets the GUID value of the node.
/// </summary>
/// <param name="propid">A __VSHPROPID or __VSHPROPID2 value of the guid property</param>
/// <param name="guid">The guid to return for the property.</param>
/// <returns>A success or failure value.</returns>
public override int GetGuidProperty(int propid, out Guid guid) {
guid = Guid.Empty;
if ((__VSHPROPID)propid == __VSHPROPID.VSHPROPID_ProjectIDGuid) {
guid = this.ProjectIDGuid;
} else if (propid == (int)__VSHPROPID.VSHPROPID_CmdUIGuid) {
guid = this.ProjectGuid;
} else if ((__VSHPROPID2)propid == __VSHPROPID2.VSHPROPID_ProjectDesignerEditor && this.SupportsProjectDesigner) {
guid = this.ProjectDesignerEditor;
} else {
base.GetGuidProperty(propid, out guid);
}
if (guid.CompareTo(Guid.Empty) == 0) {
return VSConstants.DISP_E_MEMBERNOTFOUND;
}
return VSConstants.S_OK;
}
/// <summary>
/// Sets Guid properties for the project node.
/// </summary>
/// <param name="propid">A __VSHPROPID or __VSHPROPID2 value of the guid property</param>
/// <param name="guid">The guid value to set.</param>
/// <returns>A success or failure value.</returns>
public override int SetGuidProperty(int propid, ref Guid guid) {
switch ((__VSHPROPID)propid) {
case __VSHPROPID.VSHPROPID_ProjectIDGuid:
this.ProjectIDGuid = guid;
return VSConstants.S_OK;
}
return VSConstants.DISP_E_MEMBERNOTFOUND;
}
/// <summary>
/// Removes items from the hierarchy.
/// </summary>
/// <devdoc>Project overwrites this.</devdoc>
public override void Remove(bool removeFromStorage) {
// the project will not be deleted from disk, just removed
if (removeFromStorage) {
return;
}
// Remove the entire project from the solution
IVsSolution solution = this.Site.GetService(typeof(SVsSolution)) as IVsSolution;
uint iOption = 1; // SLNSAVEOPT_PromptSave
ErrorHandler.ThrowOnFailure(solution.CloseSolutionElement(iOption, this.GetOuterInterface<IVsHierarchy>(), 0));
}
/// <summary>
/// Gets the moniker for the project node. That is the full path of the project file.
/// </summary>
/// <returns>The moniker for the project file.</returns>
public override string GetMkDocument() {
Debug.Assert(!String.IsNullOrEmpty(this.filename));
Debug.Assert(this.BaseURI != null && !String.IsNullOrEmpty(this.BaseURI.AbsoluteUrl));
return CommonUtils.GetAbsoluteFilePath(this.BaseURI.AbsoluteUrl, this.filename);
}
/// <summary>
/// Disposes the project node object.
/// </summary>
/// <param name="disposing">Flag determining ehether it was deterministic or non deterministic clean up.</param>
protected override void Dispose(bool disposing) {
if (isDisposed) {
return;
}
try {
try {
UnRegisterProject();
} finally {
try {
RegisterClipboardNotifications(false);
} finally {
buildEngine = null;
}
}
if (buildProject != null) {
buildProject.ProjectCollection.UnloadProject(buildProject);
buildProject.ProjectCollection.UnloadProject(buildProject.Xml);
SetBuildProject(null);
}
var logger = BuildLogger as IDisposable;
BuildLogger = null;
if (logger != null) {
logger.Dispose();
}
var tasks = taskProvider;
taskProvider = null;
if (tasks != null) {
tasks.Dispose();
}
isClosing = true;
isClosed = false;
if (null != imageHandler) {
imageHandler.Close();
imageHandler = null;
}
_diskNodes.Clear();
_folderBeingCreated = null;
} finally {
base.Dispose(disposing);
// Note that this isDisposed flag is separate from the base's
isDisposed = true;
isClosed = true;
isClosing = false;
projectOpened = false;
}
}
/// <summary>
/// Handles command status on the project node. If a command cannot be handled then the base should be called.
/// </summary>
/// <param name="cmdGroup">A unique identifier of the command group. The pguidCmdGroup parameter can be NULL to specify the standard group.</param>
/// <param name="cmd">The command to query status for.</param>
/// <param name="pCmdText">Pointer to an OLECMDTEXT structure in which to return the name and/or status information of a single command. Can be NULL to indicate that the caller does not require this information.</param>
/// <param name="result">An out parameter specifying the QueryStatusResult of the command.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) {
if (cmdGroup == VsMenus.guidStandardCommandSet97) {
switch ((VsCommands)cmd) {
case VsCommands.Copy:
case VsCommands.Paste:
case VsCommands.Cut:
case VsCommands.Rename:
case VsCommands.Exit:
case VsCommands.ProjectSettings:
case VsCommands.UnloadProject:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
case VsCommands.CancelBuild:
result |= QueryStatusResult.SUPPORTED;
if (this.buildInProcess)
result |= QueryStatusResult.ENABLED;
else
result |= QueryStatusResult.INVISIBLE;
return VSConstants.S_OK;
case VsCommands.NewFolder:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
case VsCommands.SetStartupProject:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
} else if (cmdGroup == VsMenus.guidStandardCommandSet2K) {
switch ((VsCommands2K)cmd) {
case VsCommands2K.ADDREFERENCE:
if (GetReferenceContainer() != null) {
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
} else {
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.INVISIBLE;
}
return VSConstants.S_OK;
case VsCommands2K.EXCLUDEFROMPROJECT:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.INVISIBLE;
return VSConstants.S_OK;
}
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
/// <summary>
/// Handles command execution.
/// </summary>
/// <param name="cmdGroup">Unique identifier of the command group</param>
/// <param name="cmd">The command to be executed.</param>
/// <param name="nCmdexecopt">Values describe how the object should execute the command.</param>
/// <param name="pvaIn">Pointer to a VARIANTARG structure containing input arguments. Can be NULL</param>
/// <param name="pvaOut">VARIANTARG structure to receive command output. Can be NULL.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
internal override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) {
if (cmdGroup == VsMenus.guidStandardCommandSet97) {
switch ((VsCommands)cmd) {
case VsCommands.UnloadProject:
return this.UnloadProject();
case VsCommands.CleanSel:
case VsCommands.CleanCtx:
return this.CleanProject();
}
}
return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut);
}
/// <summary>
/// Get the boolean value for the deletion of a project item
/// </summary>
/// <param name="deleteOperation">A flag that specifies the type of delete operation (delete from storage or remove from project)</param>
/// <returns>true if item can be deleted from project</returns>
internal override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) {
if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_RemoveFromProject) {
return true;
}
return false;
}
/// <summary>
/// Returns a specific Document manager to handle opening and closing of the Project(Application) Designer if projectdesigner is supported.
/// </summary>
/// <returns>Document manager object</returns>
protected internal override DocumentManager GetDocumentManager() {
if (this.SupportsProjectDesigner) {
return new ProjectDesignerDocumentManager(this);
}
return null;
}
#endregion
#region virtual methods
public virtual IEnumerable<string> GetAvailableItemNames() {
IEnumerable<string> itemTypes = new[] {
ProjectFileConstants.None,
ProjectFileConstants.Compile,
ProjectFileConstants.Content
};
var items = this.buildProject.GetItems("AvailableItemName");
itemTypes = itemTypes.Union(items.Select(x => x.EvaluatedInclude));
return itemTypes;
}
/// <summary>
/// Creates a reference node for the given file returning the node, or returns null
/// if the file doesn't represent a valid file which can be referenced.
/// </summary>
public virtual ReferenceNode CreateReferenceNodeForFile(string filename) {
#if FALSE
return new ComReferenceNode(this.ProjectMgr, selectorData);
#endif
return null;
}
/// <summary>
/// Executes a wizard.
/// </summary>
/// <param name="parentNode">The node to which the wizard should add item(s).</param>
/// <param name="itemName">The name of the file that the user typed in.</param>
/// <param name="wizardToRun">The name of the wizard to run.</param>
/// <param name="dlgOwner">The owner of the dialog box.</param>
/// <returns>A VSADDRESULT enum value describing success or failure.</returns>
public virtual VSADDRESULT RunWizard(HierarchyNode parentNode, string itemName, string wizardToRun, IntPtr dlgOwner) {
Debug.Assert(!String.IsNullOrEmpty(itemName), "The Add item dialog was passing in a null or empty item to be added to the hierrachy.");
Debug.Assert(!String.IsNullOrEmpty(this.ProjectHome), "ProjectHome is not specified for this project.");
Utilities.ArgumentNotNull("parentNode", parentNode);
Utilities.ArgumentNotNullOrEmpty("itemName", itemName);
// We just validate for length, since we assume other validation has been performed by the dlgOwner.
if (CommonUtils.GetAbsoluteFilePath(this.ProjectHome, itemName).Length >= NativeMethods.MAX_PATH) {
string errorMessage = SR.GetString(SR.PathTooLong, itemName);
if (!Utilities.IsInAutomationFunction(this.Site)) {
string title = null;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
Utilities.ShowMessageBox(this.Site, title, errorMessage, icon, buttons, defaultButton);
return VSADDRESULT.ADDRESULT_Failure;
} else {
throw new InvalidOperationException(errorMessage);
}
}
// Build up the ContextParams safearray
// [0] = Wizard type guid (bstr)
// [1] = Project name (bstr)
// [2] = ProjectItems collection (bstr)
// [3] = Local Directory (bstr)
// [4] = Filename the user typed (bstr)
// [5] = Product install Directory (bstr)
// [6] = Run silent (bool)
object[] contextParams = new object[7];
contextParams[0] = EnvDTE.Constants.vsWizardAddItem;
contextParams[1] = this.Caption;
object automationObject = parentNode.GetAutomationObject();
if (automationObject is EnvDTE.Project) {
EnvDTE.Project project = (EnvDTE.Project)automationObject;
contextParams[2] = project.ProjectItems;
} else {
// This would normally be a folder unless it is an item with subitems
EnvDTE.ProjectItem item = (EnvDTE.ProjectItem)automationObject;
contextParams[2] = item.ProjectItems;
}
contextParams[3] = this.ProjectHome;
contextParams[4] = itemName;
object objInstallationDir = null;
IVsShell shell = (IVsShell)this.GetService(typeof(IVsShell));
ErrorHandler.ThrowOnFailure(shell.GetProperty((int)__VSSPROPID.VSSPROPID_InstallDirectory, out objInstallationDir));
string installDir = CommonUtils.NormalizeDirectoryPath((string)objInstallationDir);
contextParams[5] = installDir;
contextParams[6] = true;
IVsExtensibility3 ivsExtensibility = this.GetService(typeof(IVsExtensibility)) as IVsExtensibility3;
Debug.Assert(ivsExtensibility != null, "Failed to get IVsExtensibility3 service");
if (ivsExtensibility == null) {
return VSADDRESULT.ADDRESULT_Failure;
}
// Determine if we have the trust to run this wizard.
IVsDetermineWizardTrust wizardTrust = this.GetService(typeof(SVsDetermineWizardTrust)) as IVsDetermineWizardTrust;
if (wizardTrust != null) {
Guid guidProjectAdding = Guid.Empty;
ErrorHandler.ThrowOnFailure(wizardTrust.OnWizardInitiated(wizardToRun, ref guidProjectAdding));
}
int wizResultAsInt;
try {
Array contextParamsAsArray = contextParams;
int result = ivsExtensibility.RunWizardFile(wizardToRun, (int)dlgOwner, ref contextParamsAsArray, out wizResultAsInt);
if (!ErrorHandler.Succeeded(result) && result != VSConstants.OLE_E_PROMPTSAVECANCELLED) {
ErrorHandler.ThrowOnFailure(result);
}
} finally {
if (wizardTrust != null) {
ErrorHandler.ThrowOnFailure(wizardTrust.OnWizardCompleted());
}
}
EnvDTE.wizardResult wizardResult = (EnvDTE.wizardResult)wizResultAsInt;
switch (wizardResult) {
default:
return VSADDRESULT.ADDRESULT_Cancel;
case wizardResult.wizardResultSuccess:
return VSADDRESULT.ADDRESULT_Success;
case wizardResult.wizardResultFailure:
return VSADDRESULT.ADDRESULT_Failure;
}
}
/// <summary>
/// This overrides the base class method to show the VS 2005 style Add reference dialog. The ProjectNode implementation
/// shows the VS 2003 style Add Reference dialog.
/// </summary>
/// <returns>S_OK if succeeded. Failure other wise</returns>
public virtual int AddProjectReference() {
IVsComponentSelectorDlg2 componentDialog;
Guid guidEmpty = Guid.Empty;
VSCOMPONENTSELECTORTABINIT[] tabInit = new VSCOMPONENTSELECTORTABINIT[4];
string strBrowseLocations = Path.GetDirectoryName(ProjectHome);
//Add the Project page
tabInit[0].dwSize = (uint)Marshal.SizeOf(typeof(VSCOMPONENTSELECTORTABINIT));
// Tell the Add Reference dialog to call hierarchies GetProperty with the following
// propID to enable filtering out ourself from the Project to Project reference
tabInit[0].varTabInitInfo = (int)__VSHPROPID.VSHPROPID_ShowProjInSolutionPage;
tabInit[0].guidTab = VSConstants.GUID_SolutionPage;
// Add the Browse for file page
tabInit[1].dwSize = (uint)Marshal.SizeOf(typeof(VSCOMPONENTSELECTORTABINIT));
tabInit[1].guidTab = VSConstants.GUID_COMPlusPage;
tabInit[1].varTabInitInfo = 0;
// Add the Browse for file page
tabInit[2].dwSize = (uint)Marshal.SizeOf(typeof(VSCOMPONENTSELECTORTABINIT));
tabInit[2].guidTab = VSConstants.GUID_BrowseFilePage;
tabInit[2].varTabInitInfo = 0;
// Add the WebPI page
tabInit[3].dwSize = (uint)Marshal.SizeOf(typeof(VSCOMPONENTSELECTORTABINIT));
tabInit[3].guidTab = typeof(WebPiComponentPickerControl).GUID;
tabInit[3].varTabInitInfo = 0;
uint pX = 0, pY = 0;
componentDialog = GetService(typeof(SVsComponentSelectorDlg)) as IVsComponentSelectorDlg2;
try {
// call the container to open the add reference dialog.
if (componentDialog != null) {
// Let the project know not to show itself in the Add Project Reference Dialog page
ShowProjectInSolutionPage = false;
// call the container to open the add reference dialog.
ErrorHandler.ThrowOnFailure(componentDialog.ComponentSelectorDlg2(
(System.UInt32)(__VSCOMPSELFLAGS.VSCOMSEL_MultiSelectMode | __VSCOMPSELFLAGS.VSCOMSEL_IgnoreMachineName),
(IVsComponentUser)this,
0,
null,
SR.GetString(SR.AddReferenceDialogTitle), // Title
"VS.AddReference", // Help topic
ref pX,
ref pY,
(uint)tabInit.Length,
tabInit,
ref guidEmpty,
AddReferenceExtensions.Replace('|', '\0') + "\0",
ref strBrowseLocations));
}
} catch (COMException e) {
Trace.WriteLine("Exception : " + e.Message);
return e.ErrorCode;
} finally {
// Let the project know it can show itself in the Add Project Reference Dialog page
ShowProjectInSolutionPage = true;
}
return VSConstants.S_OK;
}
protected virtual string AddReferenceExtensions {
get {
return SR.GetString(SR.AddReferenceExtensions);
}
}
/// <summary>
/// Returns the Compiler associated to the project
/// </summary>
/// <returns>Null</returns>
public virtual ICodeCompiler GetCompiler() {
return null;
}
/// <summary>
/// Override this method if you have your own project specific
/// subclass of ProjectOptions
/// </summary>
/// <returns>This method returns a new instance of the ProjectOptions base class.</returns>
public virtual CompilerParameters CreateProjectOptions() {
return new CompilerParameters();
}
/// <summary>
/// Loads a project file. Called from the factory CreateProject to load the project.
/// </summary>
/// <param name="fileName">File name of the project that will be created. </param>
/// <param name="location">Location where the project will be created.</param>
/// <param name="name">If applicable, the name of the template to use when cloning a new project.</param>
/// <param name="flags">Set of flag values taken from the VSCREATEPROJFLAGS enumeration.</param>
/// <param name="iidProject">Identifier of the interface that the caller wants returned. </param>
/// <param name="canceled">An out parameter specifying if the project creation was canceled</param>
public virtual void Load(string fileName, string location, string name, uint flags, ref Guid iidProject, out int canceled) {
using (new DebugTimer("ProjectLoad")) {
_diskNodes.Clear();
bool successful = false;
try {
this.disableQueryEdit = true;
// set up internal members and icons
canceled = 0;
this.ProjectMgr = this;
if ((flags & (uint)__VSCREATEPROJFLAGS.CPF_CLONEFILE) == (uint)__VSCREATEPROJFLAGS.CPF_CLONEFILE) {
// we need to generate a new guid for the project
this.projectIdGuid = Guid.NewGuid();
} else {
this.SetProjectGuidFromProjectFile();
}
// Ensure we have a valid build engine.
this.buildEngine = this.buildEngine ?? MSBuild.ProjectCollection.GlobalProjectCollection;
// based on the passed in flags, this either reloads/loads a project, or tries to create a new one
// now we create a new project... we do that by loading the template and then saving under a new name
// we also need to copy all the associated files with it.
if ((flags & (uint)__VSCREATEPROJFLAGS.CPF_CLONEFILE) == (uint)__VSCREATEPROJFLAGS.CPF_CLONEFILE) {
Debug.Assert(File.Exists(fileName), "Invalid filename passed to load the project. A valid filename is expected");
// This should be a very fast operation if the build project is already initialized by the Factory.
SetBuildProject(Utilities.ReinitializeMsBuildProject(this.buildEngine, fileName, this.buildProject));
// Compute the file name
// We try to solve two problems here. When input comes from a wizzard in case of zipped based projects
// the parameters are different.
// In that case the filename has the new filename in a temporay path.
// First get the extension from the template.
// Then get the filename from the name.
// Then create the new full path of the project.
string extension = Path.GetExtension(fileName);
string tempName = String.Empty;
// We have to be sure that we are not going to lose data here. If the project name is a.b.c then for a project that was based on a zipped template(the wizard calls us) GetFileNameWithoutExtension will suppress "c".
// We are going to check if the parameter "name" is extension based and the extension is the same as the one from the "filename" parameter.
string tempExtension = Path.GetExtension(name);
if (!String.IsNullOrEmpty(tempExtension)) {
bool isSameExtension = (String.Equals(tempExtension, extension, StringComparison.OrdinalIgnoreCase));
if (isSameExtension) {
tempName = Path.GetFileNameWithoutExtension(name);
}
// If the tempExtension is not the same as the extension that the project name comes from then assume that the project name is a dotted name.
else {
tempName = Path.GetFileName(name);
}
} else {
tempName = Path.GetFileName(name);
}
Debug.Assert(!String.IsNullOrEmpty(tempName), "Could not compute project name");
string tempProjectFileName = tempName + extension;
this.filename = CommonUtils.GetAbsoluteFilePath(location, tempProjectFileName);
// Initialize the common project properties.
this.InitializeProjectProperties();
ErrorHandler.ThrowOnFailure(this.Save(this.filename, 1, 0));
string unresolvedProjectHome = this.GetProjectProperty(CommonConstants.ProjectHome);
string basePath = CommonUtils.GetAbsoluteDirectoryPath(Path.GetDirectoryName(fileName), unresolvedProjectHome);
string baseLocation = CommonUtils.GetAbsoluteDirectoryPath(location, unresolvedProjectHome);
if (!CommonUtils.IsSameDirectory(basePath, baseLocation)) {
// now we do have the project file saved. we need to create embedded files.
foreach (MSBuild.ProjectItem item in this.BuildProject.Items) {
// Ignore the item if it is a reference or folder
if (this.FilterItemTypeToBeAddedToHierarchy(item.ItemType)) {
continue;
}
// MSBuilds tasks/targets can create items (such as object files),
// such items are not part of the project per say, and should not be displayed.
// so ignore those items.
if (!IsVisibleItem(item)) {
continue;
}
string strRelFilePath = item.EvaluatedInclude;
string strPathToFile;
string newFileName;
// taking the base name from the project template + the relative pathname,
// and you get the filename
strPathToFile = CommonUtils.GetAbsoluteFilePath(basePath, strRelFilePath);
// the new path should be the base dir of the new project (location) + the rel path of the file
newFileName = CommonUtils.GetAbsoluteFilePath(baseLocation, strRelFilePath);
// now the copy file
AddFileFromTemplate(strPathToFile, newFileName);
}
FinishProjectCreation(basePath, baseLocation);
}
} else {
this.filename = fileName;
}
_diskNodes[this.filename] = this;
// now reload to fix up references
this.Reload();
successful = true;
} finally {
this.disableQueryEdit = false;
if (!successful) {
this.Close();
}
}
}
}
public override void Close() {
projectOpened = false;
isClosing = true;
if (taskProvider != null) {
taskProvider.Tasks.Clear();
}
var autoObject = GetAutomationObject() as Automation.OAProject;
if (autoObject != null) {
autoObject.Dispose();
}
this.configProvider = null;
try {
// Walk the tree and close all nodes.
// This has to be done before the project closes, since we want
// state still available for the ProjectMgr on the nodes
// when nodes are closing.
CloseAllNodes(this);
} finally {
// HierarchyNode.Close() will also call Dispose on us
base.Close();
}
}
/// <summary>
/// Performs any new project initialization after the MSBuild project
/// has been constructed and template files copied to the project directory.
/// </summary>
protected virtual void FinishProjectCreation(string sourceFolder, string destFolder) {
}
/// <summary>
/// Called to add a file to the project from a template.
/// Override to do it yourself if you want to customize the file
/// </summary>
/// <param name="source">Full path of template file</param>
/// <param name="target">Full path of file once added to the project</param>
public virtual void AddFileFromTemplate(string source, string target) {
Utilities.ArgumentNotNullOrEmpty("source", source);
Utilities.ArgumentNotNullOrEmpty("target", target);
try {
string directory = Path.GetDirectoryName(target);
if (!String.IsNullOrEmpty(directory) && !Directory.Exists(directory)) {
Directory.CreateDirectory(directory);
}
File.Copy(source, target, true);
// best effort to reset the ReadOnly attribute
File.SetAttributes(target, File.GetAttributes(target) & ~FileAttributes.ReadOnly);
} catch (IOException e) {
Trace.WriteLine("Exception : " + e.Message);
} catch (UnauthorizedAccessException e) {
Trace.WriteLine("Exception : " + e.Message);
} catch (ArgumentException e) {
Trace.WriteLine("Exception : " + e.Message);
} catch (NotSupportedException e) {
Trace.WriteLine("Exception : " + e.Message);
}
}
/// <summary>
/// Called when the project opens an editor window for the given file
/// </summary>
public virtual void OnOpenItem(string fullPathToSourceFile) {
}
/// <summary>
/// This add methos adds the "key" item to the hierarchy, potentially adding other subitems in the process
/// This method may recurse if the parent is an other subitem
///
/// </summary>
/// <param name="subitems">List of subitems not yet added to the hierarchy</param>
/// <param name="key">Key to retrieve the target item from the subitems list</param>
/// <returns>Newly added node</returns>
/// <remarks>If the parent node was found we add the dependent item to it otherwise we add the item ignoring the "DependentUpon" metatdata</remarks>
protected virtual HierarchyNode AddDependentFileNode(IDictionary<String, MSBuild.ProjectItem> subitems, string key) {
Utilities.ArgumentNotNull("subitems", subitems);
MSBuild.ProjectItem item = subitems[key];
subitems.Remove(key);
HierarchyNode newNode;
HierarchyNode parent = null;
string dependentOf = item.GetMetadataValue(ProjectFileConstants.DependentUpon);
Debug.Assert(String.Compare(dependentOf, key, StringComparison.OrdinalIgnoreCase) != 0, "File dependent upon itself is not valid. Ignoring the DependentUpon metadata");
if (subitems.ContainsKey(dependentOf)) {
// The parent item is an other subitem, so recurse into this method to add the parent first
parent = AddDependentFileNode(subitems, dependentOf);
} else {
// See if the parent node already exist in the hierarchy
uint parentItemID;
string path = CommonUtils.GetAbsoluteFilePath(this.ProjectHome, dependentOf);
if (ErrorHandler.Succeeded(this.ParseCanonicalName(path, out parentItemID)) &&
parentItemID != 0)
parent = this.NodeFromItemId(parentItemID);
Debug.Assert(parent != null, "File dependent upon a non existing item or circular dependency. Ignoring the DependentUpon metadata");
}
// If the parent node was found we add the dependent item to it otherwise we add the item ignoring the "DependentUpon" metatdata
if (parent != null)
newNode = this.AddDependentFileNodeToNode(item, parent);
else
newNode = this.AddIndependentFileNode(item, GetItemParentNode(item));
return newNode;
}
/// <summary>
/// Do the build by invoking msbuild
/// </summary>
internal virtual void BuildAsync(uint vsopts, string config, IVsOutputWindowPane output, string target, Action<MSBuildResult, string> uiThreadCallback) {
BuildPrelude(output);
SetBuildConfigurationProperties(config);
DoAsyncMSBuildSubmission(target, uiThreadCallback);
}
/// <summary>
/// Return the value of a project property
/// </summary>
/// <param name="propertyName">Name of the property to get</param>
/// <param name="resetCache">True to avoid using the cache</param>
/// <returns>null if property does not exist, otherwise value of the property</returns>
public virtual string GetProjectProperty(string propertyName, bool resetCache) {
Site.GetUIThread().MustBeCalledFromUIThread();
MSBuildExecution.ProjectPropertyInstance property = GetMsBuildProperty(propertyName, resetCache);
if (property == null)
return null;
return property.EvaluatedValue;
}
/// <summary>
/// Return the value of a project property in it's unevalauted form.
///
/// New in 1.5.
/// </summary>
/// <param name="propertyName">Name of the property to get</param>
public virtual string GetUnevaluatedProperty(string propertyName) {
Site.GetUIThread().MustBeCalledFromUIThread();
var res = this.buildProject.GetProperty(propertyName);
if (res != null) {
return res.UnevaluatedValue;
}
return null;
}
/// <summary>
/// Set value of project property
/// </summary>
/// <param name="propertyName">Name of property</param>
/// <param name="propertyValue">Value of property</param>
public virtual void SetProjectProperty(string propertyName, string propertyValue) {
Utilities.ArgumentNotNull("propertyName", propertyName);
Site.GetUIThread().MustBeCalledFromUIThread();
var oldValue = GetUnevaluatedProperty(propertyName) ?? string.Empty;
propertyValue = propertyValue ?? string.Empty;
if (oldValue.Equals(propertyValue, StringComparison.Ordinal)) {
// Property is unchanged or unspecified, so don't set it.
return;
}
// Check out the project file.
if (!this.QueryEditProjectFile(false)) {
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
var newProp = this.buildProject.SetProperty(propertyName, propertyValue);
RaiseProjectPropertyChanged(propertyName, oldValue, propertyValue);
// property cache will need to be updated
this.currentConfig = null;
}
public virtual CompilerParameters GetProjectOptions(string config) {
// This needs to be commented out because if you build for Debug the properties from the Debug
// config are cached. When you change configurations the old props are still cached, and
// building for release the properties from the Debug config are used. This may not be the best
// fix as every time you get properties the objects are reloaded, so for perf it is bad, but
// for making it work it is necessary (reload props when a config is changed?).
////if(this.options != null)
//// return this.options;
CompilerParameters options = CreateProjectOptions();
if (config == null)
return options;
options.GenerateExecutable = true;
this.SetConfiguration(config);
string outputPath = this.GetOutputPath(this.currentConfig);
if (!String.IsNullOrEmpty(outputPath)) {
// absolutize relative to project folder location
outputPath = CommonUtils.GetAbsoluteDirectoryPath(this.ProjectHome, outputPath);
}
// Set some default values
options.OutputAssembly = outputPath + GetAssemblyName(config);
string outputtype = GetProjectProperty(ProjectFileConstants.OutputType, false);
if (!string.IsNullOrEmpty(outputtype)) {
outputtype = outputtype.ToLower(CultureInfo.InvariantCulture);
}
options.MainClass = GetProjectProperty("StartupObject", false);
// other settings from CSharp we may want to adopt at some point...
// AssemblyKeyContainerName = "" //This is the key file used to sign the interop assembly generated when importing a com object via add reference
// AssemblyOriginatorKeyFile = ""
// DelaySign = "false"
// DefaultClientScript = "JScript"
// DefaultHTMLPageLayout = "Grid"
// DefaultTargetSchema = "IE50"
// PreBuildEvent = ""
// PostBuildEvent = ""
// RunPostBuildEvent = "OnBuildSuccess"
if (GetBoolAttr(this.currentConfig, "DebugSymbols")) {
options.IncludeDebugInformation = true;
}
if (GetBoolAttr(this.currentConfig, "RegisterForComInterop")) {
}
if (GetBoolAttr(this.currentConfig, "RemoveIntegerChecks")) {
}
if (GetBoolAttr(this.currentConfig, "TreatWarningsAsErrors")) {
options.TreatWarningsAsErrors = true;
}
var warningLevel = GetProjectProperty("WarningLevel", resetCache: false);
if (warningLevel != null) {
try {
options.WarningLevel = Int32.Parse(warningLevel, CultureInfo.InvariantCulture);
} catch (ArgumentNullException e) {
Trace.WriteLine("Exception : " + e.Message);
} catch (ArgumentException e) {
Trace.WriteLine("Exception : " + e.Message);
} catch (FormatException e) {
Trace.WriteLine("Exception : " + e.Message);
} catch (OverflowException e) {
Trace.WriteLine("Exception : " + e.Message);
}
}
return options;
}
private string GetOutputPath(MSBuildExecution.ProjectInstance properties) {
return properties.GetPropertyValue("OutputPath");
}
private bool GetBoolAttr(MSBuildExecution.ProjectInstance properties, string name) {
string s = properties.GetPropertyValue(name);
return (s != null && s.ToUpperInvariant().Trim() == "TRUE");
}
public virtual bool GetBoolAttr(string config, string name) {
SetConfiguration(config);
try {
return GetBoolAttr(currentConfig, name);
} finally {
SetCurrentConfiguration();
}
}
/// <summary>
/// Get the assembly name for a given configuration
/// </summary>
/// <param name="config">the matching configuration in the msbuild file</param>
/// <returns>assembly name</returns>
public virtual string GetAssemblyName(string config) {
SetConfiguration(config);
try {
var name = currentConfig.GetPropertyValue(ProjectFileConstants.AssemblyName) ?? Caption;
var outputType = currentConfig.GetPropertyValue(ProjectFileConstants.OutputType);
if ("library".Equals(outputType, StringComparison.OrdinalIgnoreCase)) {
name += ".dll";
} else {
name += ".exe";
}
return name;
} finally {
SetCurrentConfiguration();
}
}
/// <summary>
/// Determines whether a file is a code file.
/// </summary>
/// <param name="fileName">Name of the file to be evaluated</param>
/// <returns>false by default for any fileName</returns>
public virtual bool IsCodeFile(string fileName) {
return false;
}
public virtual string[] CodeFileExtensions {
get {
return new string[0];
}
}
/// <summary>
/// Determines whether the given file is a resource file (resx file).
/// </summary>
/// <param name="fileName">Name of the file to be evaluated.</param>
/// <returns>true if the file is a resx file, otherwise false.</returns>
public virtual bool IsEmbeddedResource(string fileName) {
return String.Equals(Path.GetExtension(fileName), ".ResX", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Create a file node based on an msbuild item.
/// </summary>
/// <param name="item">msbuild item</param>
/// <returns>FileNode added</returns>
public abstract FileNode CreateFileNode(ProjectElement item);
/// <summary>
/// Create a file node based on a string.
/// </summary>
/// <param name="file">filename of the new filenode</param>
/// <returns>File node added</returns>
public abstract FileNode CreateFileNode(string file);
/// <summary>
/// Create dependent file node based on an msbuild item
/// </summary>
/// <param name="item">msbuild item</param>
/// <returns>dependent file node</returns>
public virtual DependentFileNode CreateDependentFileNode(MsBuildProjectElement item) {
return new DependentFileNode(this, item);
}
/// <summary>
/// Create a dependent file node based on a string.
/// </summary>
/// <param name="file">filename of the new dependent file node</param>
/// <returns>Dependent node added</returns>
public virtual DependentFileNode CreateDependentFileNode(string file) {
var item = AddFileToMsBuild(file);
return this.CreateDependentFileNode(item);
}
/// <summary>
/// Walks the subpaths of a project relative path and checks if the folder nodes hierarchy is already there, if not creates it.
/// </summary>
/// <param name="strPath">Path of the folder, can be relative to project or absolute</param>
public virtual HierarchyNode CreateFolderNodes(string path, bool createOnDisk = true) {
Utilities.ArgumentNotNull("path", path);
if (Path.IsPathRooted(path)) {
// Ensure we are using a path deeper than ProjectHome
if (!CommonUtils.IsSubpathOf(ProjectHome, path)) {
throw new ArgumentException("The path is not within the project", "path");
}
path = CommonUtils.GetRelativeDirectoryPath(ProjectHome, path);
}
// If the folder already exists, return early
string strFullPath = CommonUtils.GetAbsoluteDirectoryPath(ProjectHome, path);
uint uiItemId;
if (ErrorHandler.Succeeded(ParseCanonicalName(strFullPath, out uiItemId)) &&
uiItemId != 0) {
var folder = this.NodeFromItemId(uiItemId) as FolderNode;
if (folder != null) {
// found the folder, return immediately
return folder;
}
}
string[] parts = strFullPath.Substring(ProjectHome.Length).Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0) {
// pointing at the project home, it already exists
return this;
}
path = parts[0];
string fullPath = Path.Combine(ProjectHome, path) + "\\";
string relPath = path;
HierarchyNode curParent = VerifySubFolderExists(path, fullPath, this, createOnDisk);
// now we have an array of subparts....
for (int i = 1; i < parts.Length; i++) {
if (parts[i].Length > 0) {
fullPath = Path.Combine(fullPath, parts[i]) + "\\";
relPath = Path.Combine(relPath, parts[i]);
curParent = VerifySubFolderExists(relPath, fullPath, curParent, createOnDisk);
}
}
return curParent;
}
/// <summary>
/// Defines if Node has Designer. By default we do not support designers for nodes
/// </summary>
/// <param name="itemPath">Path to item to query for designer support</param>
/// <returns>true if node has designer</returns>
public virtual bool NodeHasDesigner(string itemPath) {
return false;
}
/// <summary>
/// List of Guids of the config independent property pages. It is called by the GetProperty for VSHPROPID_PropertyPagesCLSIDList property.
/// </summary>
/// <returns></returns>
protected virtual Guid[] GetConfigurationIndependentPropertyPages() {
return new Guid[] { };
}
/// <summary>
/// Returns a list of Guids of the configuration dependent property pages. It is called by the GetProperty for VSHPROPID_CfgPropertyPagesCLSIDList property.
/// </summary>
/// <returns></returns>
protected virtual Guid[] GetConfigurationDependentPropertyPages() {
return new Guid[] { };
}
/// <summary>
/// An ordered list of guids of the prefered property pages. See <see cref="__VSHPROPID.VSHPROPID_PriorityPropertyPagesCLSIDList"/>
/// </summary>
/// <returns>An array of guids.</returns>
protected virtual Guid[] GetPriorityProjectDesignerPages() {
return new Guid[] { Guid.Empty };
}
/// <summary>
/// Takes a path and verifies that we have a node with that name.
/// It is meant to be a helper method for CreateFolderNodes().
/// For some scenario it may be useful to override.
/// </summary>
/// <param name="relativePath">The relative path to the subfolder we want to create, without a trailing \</param>
/// <param name="fullPath">the full path to the subfolder we want to verify.</param>
/// <param name="parent">the parent node where to add the subfolder if it does not exist.</param>
/// <returns>the foldernode correcsponding to the path.</returns>
protected virtual FolderNode VerifySubFolderExists(string relativePath, string fullPath, HierarchyNode parent, bool createOnDisk = true) {
Debug.Assert(!CommonUtils.HasEndSeparator(relativePath));
FolderNode folderNode = null;
uint uiItemId;
if (ErrorHandler.Succeeded(this.ParseCanonicalName(fullPath, out uiItemId)) &&
uiItemId != 0) {
Debug.Assert(this.NodeFromItemId(uiItemId) is FolderNode, "Not a FolderNode");
folderNode = (FolderNode)this.NodeFromItemId(uiItemId);
}
if (folderNode == null && fullPath != null && parent != null) {
// folder does not exist yet...
// We could be in the process of loading so see if msbuild knows about it
ProjectElement item = null;
var items = buildProject.GetItemsByEvaluatedInclude(relativePath);
if (items.Count == 0) {
items = buildProject.GetItemsByEvaluatedInclude(relativePath + "\\");
}
if (items.Count != 0) {
item = new MsBuildProjectElement(this, items.First());
} else {
item = AddFolderToMsBuild(fullPath);
}
if (createOnDisk) {
Directory.CreateDirectory(fullPath);
}
folderNode = CreateFolderNode(item);
parent.AddChild(folderNode);
}
return folderNode;
}
/// <summary>
/// To support virtual folders, override this method to return your own folder nodes
/// </summary>
/// <param name="path">Path to store for this folder</param>
/// <param name="element">Element corresponding to the folder</param>
/// <returns>A FolderNode that can then be added to the hierarchy</returns>
protected internal virtual FolderNode CreateFolderNode(ProjectElement element) {
return new FolderNode(this, element);
}
/// <summary>
/// Gets the list of selected HierarchyNode objects
/// </summary>
/// <returns>A list of HierarchyNode objects</returns>
protected internal virtual IList<HierarchyNode> GetSelectedNodes() {
// Retrieve shell interface in order to get current selection
IVsMonitorSelection monitorSelection = this.GetService(typeof(IVsMonitorSelection)) as IVsMonitorSelection;
Utilities.CheckNotNull(monitorSelection);
List<HierarchyNode> selectedNodes = new List<HierarchyNode>();
IntPtr hierarchyPtr = IntPtr.Zero;
IntPtr selectionContainer = IntPtr.Zero;
try {
// Get the current project hierarchy, project item, and selection container for the current selection
// If the selection spans multiple hierachies, hierarchyPtr is Zero
uint itemid;
IVsMultiItemSelect multiItemSelect = null;
ErrorHandler.ThrowOnFailure(monitorSelection.GetCurrentSelection(out hierarchyPtr, out itemid, out multiItemSelect, out selectionContainer));
// We only care if there are one ore more nodes selected in the tree
if (itemid != VSConstants.VSITEMID_NIL && hierarchyPtr != IntPtr.Zero) {
IVsHierarchy hierarchy = Marshal.GetObjectForIUnknown(hierarchyPtr) as IVsHierarchy;
if (itemid != VSConstants.VSITEMID_SELECTION) {
// This is a single selection. Compare hirarchy with our hierarchy and get node from itemid
if (Utilities.IsSameComObject(this, hierarchy)) {
HierarchyNode node = this.NodeFromItemId(itemid);
if (node != null) {
selectedNodes.Add(node);
}
}
} else if (multiItemSelect != null) {
// This is a multiple item selection.
//Get number of items selected and also determine if the items are located in more than one hierarchy
uint numberOfSelectedItems;
int isSingleHierarchyInt;
ErrorHandler.ThrowOnFailure(multiItemSelect.GetSelectionInfo(out numberOfSelectedItems, out isSingleHierarchyInt));
bool isSingleHierarchy = (isSingleHierarchyInt != 0);
// Now loop all selected items and add to the list only those that are selected within this hierarchy
if (!isSingleHierarchy || (isSingleHierarchy && Utilities.IsSameComObject(this, hierarchy))) {
Debug.Assert(numberOfSelectedItems > 0, "Bad number of selected itemd");
VSITEMSELECTION[] vsItemSelections = new VSITEMSELECTION[numberOfSelectedItems];
uint flags = (isSingleHierarchy) ? (uint)__VSGSIFLAGS.GSI_fOmitHierPtrs : 0;
ErrorHandler.ThrowOnFailure(multiItemSelect.GetSelectedItems(flags, numberOfSelectedItems, vsItemSelections));
foreach (VSITEMSELECTION vsItemSelection in vsItemSelections) {
if (isSingleHierarchy || Utilities.IsSameComObject(this, vsItemSelection.pHier)) {
HierarchyNode node = this.NodeFromItemId(vsItemSelection.itemid);
if (node != null) {
selectedNodes.Add(node);
}
}
}
}
}
}
} finally {
if (hierarchyPtr != IntPtr.Zero) {
Marshal.Release(hierarchyPtr);
}
if (selectionContainer != IntPtr.Zero) {
Marshal.Release(selectionContainer);
}
}
return selectedNodes;
}
/// <summary>
/// Recursevily walks the hierarchy nodes and redraws the state icons
/// </summary>
protected internal override void UpdateSccStateIcons() {
if (this.FirstChild == null) {
return;
}
for (HierarchyNode n = this.FirstChild; n != null; n = n.NextSibling) {
n.UpdateSccStateIcons();
}
}
/// <summary>
/// Handles the shows all objects command.
/// </summary>
/// <returns></returns>
protected internal virtual int ShowAllFiles() {
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
/// <summary>
/// Unloads the project.
/// </summary>
/// <returns></returns>
protected internal virtual int UnloadProject() {
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
/// <summary>
/// Handles the clean project command.
/// </summary>
/// <returns></returns>
protected virtual int CleanProject() {
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
/// <summary>
/// Reload project from project file
/// </summary>
protected virtual void Reload() {
Debug.Assert(this.buildEngine != null, "There is no build engine defined for this project");
try {
disableQueryEdit = true;
isClosed = false;
eventTriggeringFlag = ProjectNode.EventTriggering.DoNotTriggerHierarchyEvents | ProjectNode.EventTriggering.DoNotTriggerTrackerEvents;
SetBuildProject(Utilities.ReinitializeMsBuildProject(buildEngine, filename, buildProject));
// Load the guid
SetProjectGuidFromProjectFile();
ProcessReferences();
ProcessFolders();
ProcessFiles();
LoadNonBuildInformation();
InitSccInfo();
RegisterSccProject();
} finally {
isDirty = false;
eventTriggeringFlag = ProjectNode.EventTriggering.TriggerAll;
disableQueryEdit = false;
}
}
/// <summary>
/// Renames the project file
/// </summary>
/// <param name="newFile">The full path of the new project file.</param>
protected virtual void RenameProjectFile(string newFile) {
IVsUIShell shell = GetService(typeof(SVsUIShell)) as IVsUIShell;
Utilities.CheckNotNull(shell, "Could not get the UI shell from the project");
// Figure out what the new full name is
string oldFile = this.Url;
int canContinue = 0;
IVsSolution vsSolution = (IVsSolution)GetService(typeof(SVsSolution));
if (ErrorHandler.Succeeded(vsSolution.QueryRenameProject(GetOuterInterface<IVsProject>(), oldFile, newFile, 0, out canContinue))
&& canContinue != 0) {
bool isFileSame = CommonUtils.IsSamePath(oldFile, newFile);
// If file already exist and is not the same file with different casing
if (!isFileSame && File.Exists(newFile)) {
// Prompt the user for replace
string message = SR.GetString(SR.FileAlreadyExists, newFile);
if (!Utilities.IsInAutomationFunction(this.Site)) {
if (!VsShellUtilities.PromptYesNo(message, null, OLEMSGICON.OLEMSGICON_WARNING, shell)) {
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
} else {
throw new InvalidOperationException(message);
}
// Delete the destination file after making sure it is not read only
File.SetAttributes(newFile, FileAttributes.Normal);
File.Delete(newFile);
}
SuspendFileChanges fileChanges = new SuspendFileChanges(this.Site, this.filename);
fileChanges.Suspend();
try {
// Actual file rename
SaveMSBuildProjectFileAs(newFile);
if (!isFileSame) {
// Now that the new file name has been created delete the old one.
// TODO: Handle source control issues.
File.SetAttributes(oldFile, FileAttributes.Normal);
File.Delete(oldFile);
}
OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_Caption, 0);
// Update solution
ErrorHandler.ThrowOnFailure(vsSolution.OnAfterRenameProject((IVsProject)this, oldFile, newFile, 0));
ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0));
} finally {
fileChanges.Resume();
}
} else {
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
}
/// <summary>
/// Filter items that should not be processed as file items. Example: Folders and References.
/// </summary>
protected virtual bool FilterItemTypeToBeAddedToHierarchy(string itemType) {
return (String.Compare(itemType, ProjectFileConstants.Reference, StringComparison.OrdinalIgnoreCase) == 0
|| String.Compare(itemType, ProjectFileConstants.ProjectReference, StringComparison.OrdinalIgnoreCase) == 0
|| String.Compare(itemType, ProjectFileConstants.COMReference, StringComparison.OrdinalIgnoreCase) == 0
|| String.Compare(itemType, ProjectFileConstants.Folder, StringComparison.OrdinalIgnoreCase) == 0
|| String.Compare(itemType, ProjectFileConstants.WebReference, StringComparison.OrdinalIgnoreCase) == 0
|| String.Compare(itemType, ProjectFileConstants.WebReferenceFolder, StringComparison.OrdinalIgnoreCase) == 0
|| String.Compare(itemType, ProjectFileConstants.WebPiReference, StringComparison.OrdinalIgnoreCase) == 0);
}
/// <summary>
/// Associate window output pane to the build logger
/// </summary>
/// <param name="output"></param>
protected virtual void SetOutputLogger(IVsOutputWindowPane output) {
// Create our logger, if it was not specified
if (!this.useProvidedLogger || this.buildLogger == null) {
// Create the logger
var logger = new IDEBuildLogger(output, this.TaskProvider, GetOuterInterface<IVsHierarchy>());
logger.ErrorString = ErrorString;
logger.WarningString = WarningString;
var oldLogger = this.BuildLogger as IDisposable;
this.BuildLogger = logger;
if (oldLogger != null) {
oldLogger.Dispose();
}
} else {
((IDEBuildLogger)this.BuildLogger).OutputWindowPane = output;
}
}
/// <summary>
/// Set configuration properties for a specific configuration
/// </summary>
/// <param name="config">configuration name</param>
protected virtual void SetBuildConfigurationProperties(string config) {
CompilerParameters options = null;
if (!String.IsNullOrEmpty(config)) {
options = this.GetProjectOptions(config);
}
if (options != null && this.buildProject != null) {
// Make sure the project configuration is set properly
this.SetConfiguration(config);
}
}
/// <summary>
/// This execute an MSBuild target for a design-time build.
/// </summary>
/// <param name="target">Name of the MSBuild target to execute</param>
/// <returns>Result from executing the target (success/failure)</returns>
/// <remarks>
/// If you depend on the items/properties generated by the target
/// you should be aware that any call to BuildTarget on any project
/// will reset the list of generated items/properties
/// </remarks>
protected virtual MSBuildResult InvokeMsBuild(string target) {
Site.GetUIThread().MustBeCalledFromUIThread();
MSBuildResult result = MSBuildResult.Failed;
const bool designTime = true;
IVsBuildManagerAccessor accessor = this.Site.GetService(typeof(SVsBuildManagerAccessor)) as IVsBuildManagerAccessor;
BuildSubmission submission = null;
try {
// Do the actual Build
if (this.buildProject != null) {
if (!TryBeginBuild(designTime, true)) {
throw new InvalidOperationException("A build is already in progress.");
}
string[] targetsToBuild = new string[target != null ? 1 : 0];
if (target != null) {
targetsToBuild[0] = target;
}
currentConfig = BuildProject.CreateProjectInstance();
BuildRequestData requestData = new BuildRequestData(currentConfig, targetsToBuild, this.BuildProject.ProjectCollection.HostServices, BuildRequestDataFlags.ReplaceExistingProjectInstance);
submission = BuildManager.DefaultBuildManager.PendBuildRequest(requestData);
if (accessor != null) {
ErrorHandler.ThrowOnFailure(accessor.RegisterLogger(submission.SubmissionId, this.buildLogger));
}
BuildResult buildResult = submission.Execute();
result = (buildResult.OverallResult == BuildResultCode.Success) ? MSBuildResult.Successful : MSBuildResult.Failed;
}
} finally {
EndBuild(submission, designTime, true);
}
return result;
}
/// <summary>
/// Start MSBuild build submission
/// </summary>
/// <param name="target">target to build</param>
/// <param name="projectInstance">project instance to build; if null, this.BuildProject.CreateProjectInstance() is used to populate</param>
/// <param name="uiThreadCallback">callback to be run UI thread </param>
/// <returns>A Build submission instance.</returns>
protected virtual BuildSubmission DoAsyncMSBuildSubmission(string target, Action<MSBuildResult, string> uiThreadCallback) {
const bool designTime = false;
IVsBuildManagerAccessor accessor = (IVsBuildManagerAccessor)this.Site.GetService(typeof(SVsBuildManagerAccessor));
Utilities.CheckNotNull(accessor);
if (!TryBeginBuild(designTime, false)) {
if (uiThreadCallback != null) {
uiThreadCallback(MSBuildResult.Failed, target);
}
return null;
}
string[] targetsToBuild = new string[target != null ? 1 : 0];
if (target != null) {
targetsToBuild[0] = target;
}
MSBuildExecution.ProjectInstance projectInstance = BuildProject.CreateProjectInstance();
projectInstance.SetProperty(GlobalProperty.VisualStudioStyleErrors.ToString(), "true");
projectInstance.SetProperty("UTFOutput", "true");
projectInstance.SetProperty(GlobalProperty.BuildingInsideVisualStudio.ToString(), "true");
BuildProject.ProjectCollection.HostServices.SetNodeAffinity(projectInstance.FullPath, NodeAffinity.InProc);
BuildRequestData requestData = new BuildRequestData(projectInstance, targetsToBuild, this.BuildProject.ProjectCollection.HostServices, BuildRequestDataFlags.ReplaceExistingProjectInstance);
BuildSubmission submission = BuildManager.DefaultBuildManager.PendBuildRequest(requestData);
try {
if (useProvidedLogger && buildLogger != null) {
ErrorHandler.ThrowOnFailure(accessor.RegisterLogger(submission.SubmissionId, buildLogger));
}
submission.ExecuteAsync(sub => {
Site.GetUIThread().Invoke(() => {
IDEBuildLogger ideLogger = this.buildLogger as IDEBuildLogger;
if (ideLogger != null) {
ideLogger.FlushBuildOutput();
}
EndBuild(sub, designTime, false);
uiThreadCallback((sub.BuildResult.OverallResult == BuildResultCode.Success) ? MSBuildResult.Successful : MSBuildResult.Failed, target);
});
}, null);
} catch (Exception e) {
Debug.Fail(e.ToString());
EndBuild(submission, designTime, false);
if (uiThreadCallback != null) {
uiThreadCallback(MSBuildResult.Failed, target);
}
throw;
}
return submission;
}
/// <summary>
/// Initialize common project properties with default value if they are empty
/// </summary>
/// <remarks>The following common project properties are defaulted to projectName (if empty):
/// AssemblyName, Name and RootNamespace.
/// If the project filename is not set then no properties are set</remarks>
protected virtual void InitializeProjectProperties() {
// Get projectName from project filename. Return if not set
string projectName = Path.GetFileNameWithoutExtension(this.filename);
if (String.IsNullOrEmpty(projectName)) {
return;
}
if (String.IsNullOrEmpty(GetProjectProperty(ProjectFileConstants.AssemblyName))) {
SetProjectProperty(ProjectFileConstants.AssemblyName, projectName);
}
if (String.IsNullOrEmpty(GetProjectProperty(ProjectFileConstants.Name))) {
SetProjectProperty(ProjectFileConstants.Name, projectName);
}
if (String.IsNullOrEmpty(GetProjectProperty(ProjectFileConstants.RootNamespace))) {
SetProjectProperty(ProjectFileConstants.RootNamespace, projectName);
}
}
/// <summary>
/// Factory method for configuration provider
/// </summary>
/// <returns>Configuration provider created</returns>
protected abstract ConfigProvider CreateConfigProvider();
/// <summary>
/// Factory method for reference container node
/// </summary>
/// <returns>ReferenceContainerNode created</returns>
protected virtual ReferenceContainerNode CreateReferenceContainerNode() {
return new ReferenceContainerNode(this);
}
/// <summary>
/// Saves the project file on a new name.
/// </summary>
/// <param name="newFileName">The new name of the project file.</param>
/// <returns>Success value or an error code.</returns>
protected virtual int SaveAs(string newFileName) {
Debug.Assert(!String.IsNullOrEmpty(newFileName), "Cannot save project file for an empty or null file name");
Utilities.ArgumentNotNullOrEmpty(newFileName, "newFileName");
newFileName = newFileName.Trim();
string errorMessage = String.Empty;
if (newFileName.Length > NativeMethods.MAX_PATH) {
errorMessage = SR.GetString(SR.PathTooLong, newFileName);
} else {
string fileName = String.Empty;
try {
fileName = Path.GetFileNameWithoutExtension(newFileName);
}
// We want to be consistent in the error message and exception we throw. fileName could be for example #¤&%"¤&"% and that would trigger an ArgumentException on Path.IsRooted.
catch (ArgumentException) {
errorMessage = SR.GetString(SR.ErrorInvalidFileName, newFileName);
}
if (errorMessage.Length == 0) {
// If there is no filename or it starts with a leading dot issue an error message and quit.
// For some reason the save as dialog box allows to save files like "......ext"
if (String.IsNullOrEmpty(fileName) || fileName[0] == '.') {
errorMessage = SR.GetString(SR.FileNameCannotContainALeadingPeriod);
} else if (Utilities.ContainsInvalidFileNameChars(newFileName)) {
errorMessage = SR.GetString(SR.ErrorInvalidFileName, newFileName);
}
}
}
if (errorMessage.Length > 0) {
// If it is not called from an automation method show a dialog box.
if (!Utilities.IsInAutomationFunction(this.Site)) {
string title = null;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
Utilities.ShowMessageBox(this.Site, title, errorMessage, icon, buttons, defaultButton);
return VSConstants.OLE_E_PROMPTSAVECANCELLED;
}
throw new InvalidOperationException(errorMessage);
}
string oldName = this.filename;
IVsSolution solution = this.Site.GetService(typeof(IVsSolution)) as IVsSolution;
Utilities.CheckNotNull(solution, "Could not retrieve the solution form the service provider");
int canRenameContinue = 0;
ErrorHandler.ThrowOnFailure(solution.QueryRenameProject(this.GetOuterInterface<IVsProject>(), this.filename, newFileName, 0, out canRenameContinue));
if (canRenameContinue == 0) {
return VSConstants.OLE_E_PROMPTSAVECANCELLED;
}
SuspendFileChanges fileChanges = new SuspendFileChanges(this.Site, oldName);
fileChanges.Suspend();
try {
// Save the project file and project file related properties.
this.SaveMSBuildProjectFileAs(newFileName);
// TODO: If source control is enabled check out the project file.
//Redraw.
this.OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_Caption, 0);
ErrorHandler.ThrowOnFailure(solution.OnAfterRenameProject(this, oldName, this.filename, 0));
IVsUIShell shell = this.Site.GetService(typeof(SVsUIShell)) as IVsUIShell;
Utilities.CheckNotNull(shell, "Could not get the UI shell from the project");
ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0));
} finally {
fileChanges.Resume();
}
return VSConstants.S_OK;
}
/// <summary>
/// Saves project file related information to the new file name. It also calls msbuild API to save the project file.
/// It is called by the SaveAs method and the SetEditLabel before the project file rename related events are triggered.
/// An implementer can override this method to provide specialized semantics on how the project file is renamed in the msbuild file.
/// </summary>
/// <param name="newFileName">The new full path of the project file</param>
protected virtual void SaveMSBuildProjectFileAs(string newFileName) {
Debug.Assert(!String.IsNullOrEmpty(newFileName), "Cannot save project file for an empty or null file name");
string newProjectHome = CommonUtils.GetRelativeDirectoryPath(Path.GetDirectoryName(newFileName), ProjectHome);
buildProject.SetProperty(CommonConstants.ProjectHome, newProjectHome);
buildProject.FullPath = newFileName;
_diskNodes.Remove(this.filename);
this.filename = newFileName;
_diskNodes[this.filename] = this;
string newFileNameWithoutExtension = Path.GetFileNameWithoutExtension(newFileName);
// Refresh solution explorer
SetProjectProperty(ProjectFileConstants.Name, newFileNameWithoutExtension);
// Saves the project file on disk.
SaveMSBuildProjectFile(newFileName);
}
/// <summary>
/// Adds a file to the msbuild project.
/// </summary>
/// <param name="file">The file to be added.</param>
/// <returns>A Projectelement describing the newly added file.</returns>
internal virtual MsBuildProjectElement AddFileToMsBuild(string file) {
MsBuildProjectElement newItem;
string itemPath = CommonUtils.GetRelativeFilePath(ProjectHome, file);
Debug.Assert(!Path.IsPathRooted(itemPath), "Cannot add item with full path.");
if (this.IsCodeFile(itemPath)) {
newItem = this.CreateMsBuildFileItem(itemPath, ProjectFileConstants.Compile);
newItem.SetMetadata(ProjectFileConstants.SubType, ProjectFileAttributeValue.Code);
} else if (this.IsEmbeddedResource(itemPath)) {
newItem = this.CreateMsBuildFileItem(itemPath, ProjectFileConstants.EmbeddedResource);
} else {
newItem = this.CreateMsBuildFileItem(itemPath, ProjectFileConstants.Content);
newItem.SetMetadata(ProjectFileConstants.SubType, ProjectFileConstants.Content);
}
return newItem;
}
/// <summary>
/// Adds a folder to the msbuild project.
/// </summary>
/// <param name="folder">The folder to be added.</param>
/// <returns>A ProjectElement describing the newly added folder.</returns>
protected virtual ProjectElement AddFolderToMsBuild(string folder) {
ProjectElement newItem;
if (Path.IsPathRooted(folder)) {
folder = CommonUtils.GetRelativeDirectoryPath(ProjectHome, folder);
Debug.Assert(!Path.IsPathRooted(folder), "Cannot add item with full path.");
}
newItem = this.CreateMsBuildFileItem(folder, ProjectFileConstants.Folder);
return newItem;
}
const int E_CANCEL_FILE_ADD = unchecked((int)0xA0010001); // Severity = Error, Customer Bit set, Facility = 1, Error = 1
/// <summary>
/// Checks to see if the user wants to overwrite the specified file name.
///
/// Returns:
/// E_ABORT if we disallow the user to overwrite the file
/// OLECMDERR_E_CANCELED if the user wants to cancel
/// S_OK if the user wants to overwrite
/// E_CANCEL_FILE_ADD (0xA0010001) if the user doesn't want to overwrite and wants to abort the larger transaction
/// </summary>
/// <param name="originalFileName"></param>
/// <param name="computedNewFileName"></param>
/// <param name="canCancel"></param>
/// <returns></returns>
protected int CanOverwriteExistingItem(string originalFileName, string computedNewFileName, bool inProject = true) {
if (String.IsNullOrEmpty(originalFileName) || String.IsNullOrEmpty(computedNewFileName)) {
return VSConstants.E_INVALIDARG;
}
string title = String.Empty;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
// File already exists in project... message box
string message = SR.GetString(inProject ? SR.FileAlreadyInProject : SR.FileAlreadyExists, Path.GetFileName(computedNewFileName));
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_QUERY;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_YESNO;
int msgboxResult = Utilities.ShowMessageBox(this.Site, title, message, icon, buttons, defaultButton);
if (msgboxResult == NativeMethods.IDCANCEL) {
return (int)E_CANCEL_FILE_ADD;
} else if (msgboxResult != NativeMethods.IDYES) {
return (int)OleConstants.OLECMDERR_E_CANCELED;
}
return VSConstants.S_OK;
}
/// <summary>
/// Adds a new file node to the hierarchy.
/// </summary>
/// <param name="parentNode">The parent of the new fileNode</param>
/// <param name="fileName">The file name</param>
protected virtual void AddNewFileNodeToHierarchy(HierarchyNode parentNode, string fileName) {
Utilities.ArgumentNotNull("parentNode", parentNode);
HierarchyNode child;
// In the case of subitem, we want to create dependent file node
// and set the DependentUpon property
if (this.canFileNodesHaveChilds && (parentNode is FileNode || parentNode is DependentFileNode)) {
child = this.CreateDependentFileNode(fileName);
child.ItemNode.SetMetadata(ProjectFileConstants.DependentUpon, parentNode.ItemNode.GetMetadata(ProjectFileConstants.Include));
// Make sure to set the HasNameRelation flag on the dependent node if it is related to the parent by name
if (!child.HasParentNodeNameRelation && string.Compare(child.GetRelationalName(), parentNode.GetRelationalName(), StringComparison.OrdinalIgnoreCase) == 0) {
child.HasParentNodeNameRelation = true;
}
} else {
//Create and add new filenode to the project
child = this.CreateFileNode(fileName);
}
parentNode.AddChild(child);
// TODO : Revisit the VSADDFILEFLAGS here. Can it be a nested project?
this.tracker.OnItemAdded(fileName, VSADDFILEFLAGS.VSADDFILEFLAGS_NoFlags);
}
/// <summary>
/// Defines whther the current mode of the project is in a supress command mode.
/// </summary>
/// <returns></returns>
protected internal virtual bool IsCurrentStateASuppressCommandsMode() {
if (VsShellUtilities.IsSolutionBuilding(this.Site)) {
return true;
}
DBGMODE dbgMode = VsShellUtilities.GetDebugMode(this.Site) & ~DBGMODE.DBGMODE_EncMask;
if (dbgMode == DBGMODE.DBGMODE_Run || dbgMode == DBGMODE.DBGMODE_Break) {
return true;
}
return false;
}
/// <summary>
/// This is the list of output groups that the configuration object should
/// provide.
/// The first string is the name of the group.
/// The second string is the target name (MSBuild) for that group.
///
/// To add/remove OutputGroups, simply override this method and edit the list.
///
/// To get nice display names and description for your groups, override:
/// - GetOutputGroupDisplayName
/// - GetOutputGroupDescription
/// </summary>
/// <returns>List of output group name and corresponding MSBuild target</returns>
protected internal virtual IList<KeyValuePair<string, string>> GetOutputGroupNames() {
return new List<KeyValuePair<string, string>>(outputGroupNames);
}
/// <summary>
/// Get the display name of the given output group.
/// </summary>
/// <param name="canonicalName">Canonical name of the output group</param>
/// <returns>Display name</returns>
protected internal virtual string GetOutputGroupDisplayName(string canonicalName) {
string result = SR.GetString("Output" + canonicalName);
if (String.IsNullOrEmpty(result))
result = canonicalName;
return result;
}
/// <summary>
/// Get the description of the given output group.
/// </summary>
/// <param name="canonicalName">Canonical name of the output group</param>
/// <returns>Description</returns>
protected internal virtual string GetOutputGroupDescription(string canonicalName) {
string result = SR.GetString("Output" + canonicalName + "Description");
if (String.IsNullOrEmpty(result))
result = canonicalName;
return result;
}
/// <summary>
/// Set the configuration in MSBuild.
/// This does not get persisted and is used to evaluate msbuild conditions
/// which are based on the $(Configuration) property.
/// </summary>
protected internal virtual void SetCurrentConfiguration() {
// Can't ask for the active config until the project is opened, so do nothing in that scenario
if (!IsProjectOpened)
return;
var solutionBuild = (IVsSolutionBuildManager)GetService(typeof(SVsSolutionBuildManager));
IVsProjectCfg[] cfg = new IVsProjectCfg[1];
ErrorHandler.ThrowOnFailure(
solutionBuild.FindActiveProjectCfg(IntPtr.Zero, IntPtr.Zero, GetOuterHierarchy(), cfg));
string name;
ErrorHandler.ThrowOnFailure(cfg[0].get_CanonicalName(out name));
SetConfiguration(name);
}
/// <summary>
/// Set the configuration property in MSBuild.
/// This does not get persisted and is used to evaluate msbuild conditions
/// which are based on the $(Configuration) property.
/// </summary>
/// <param name="config">Configuration name</param>
protected internal virtual void SetConfiguration(string config) {
Utilities.ArgumentNotNull("config", config);
// Can't ask for the active config until the project is opened, so do nothing in that scenario
if (!IsProjectOpened)
return;
bool propertiesChanged = this.BuildProject.SetGlobalProperty(ProjectFileConstants.Configuration, config);
if (this.currentConfig == null || propertiesChanged) {
this.currentConfig = this.BuildProject.CreateProjectInstance();
}
}
/// <summary>
/// Loads reference items from the project file into the hierarchy.
/// </summary>
protected internal virtual void ProcessReferences() {
IReferenceContainer container = GetReferenceContainer();
if (null == container) {
// Process References
ReferenceContainerNode referencesFolder = CreateReferenceContainerNode();
if (null == referencesFolder) {
// This project type does not support references or there is a problem
// creating the reference container node.
// In both cases there is no point to try to process references, so exit.
return;
}
this.AddChild(referencesFolder);
container = referencesFolder;
}
// Load the referernces.
container.LoadReferencesFromBuildProject(buildProject);
}
/// <summary>
/// Loads folders from the project file into the hierarchy.
/// </summary>
protected internal virtual void ProcessFolders() {
// Process Folders (useful to persist empty folder)
foreach (MSBuild.ProjectItem folder in this.buildProject.GetItems(ProjectFileConstants.Folder).ToArray()) {
string strPath = folder.EvaluatedInclude;
// We do not need any special logic for assuring that a folder is only added once to the ui hierarchy.
// The below method will only add once the folder to the ui hierarchy
this.CreateFolderNodes(strPath, false);
}
}
/// <summary>
/// Loads file items from the project file into the hierarchy.
/// </summary>
protected internal virtual void ProcessFiles() {
List<String> subitemsKeys = new List<String>();
Dictionary<String, MSBuild.ProjectItem> subitems = new Dictionary<String, MSBuild.ProjectItem>();
// Define a set for our build items. The value does not really matter here.
Dictionary<String, MSBuild.ProjectItem> items = new Dictionary<String, MSBuild.ProjectItem>();
// Process Files
foreach (MSBuild.ProjectItem item in this.buildProject.Items.ToArray()) // copy the array, we could add folders while enumerating
{
// Ignore the item if it is a reference or folder
if (this.FilterItemTypeToBeAddedToHierarchy(item.ItemType))
continue;
// Check if the item is imported. If it is we'll only show it in the
// project if it is a Visible item meta data. Visible can also be used
// to hide non-imported items.
if (!IsVisibleItem(item)) {
continue;
}
// If the item is already contained do nothing.
// TODO: possibly report in the error list that the the item is already contained in the project file similar to Language projects.
if (items.ContainsKey(item.EvaluatedInclude.ToUpperInvariant()))
continue;
// Make sure that we do not want to add the item, dependent, or independent twice to the ui hierarchy
items.Add(item.EvaluatedInclude.ToUpperInvariant(), item);
string dependentOf = item.GetMetadataValue(ProjectFileConstants.DependentUpon);
string link = item.GetMetadataValue(ProjectFileConstants.Link);
if (!String.IsNullOrWhiteSpace(link)) {
if (Path.IsPathRooted(link)) {
// ignore fully rooted link paths.
continue;
}
if (!Path.IsPathRooted(item.EvaluatedInclude)) {
var itemPath = CommonUtils.GetAbsoluteFilePath(ProjectHome, item.EvaluatedInclude);
if (CommonUtils.IsSubpathOf(ProjectHome, itemPath)) {
// linked file which lives in our directory, don't allow that.
continue;
}
}
var linkPath = CommonUtils.GetAbsoluteFilePath(ProjectHome, link);
if (!CommonUtils.IsSubpathOf(ProjectHome, linkPath)) {
// relative path outside of project, don't allow that.
continue;
}
}
if (!this.CanFileNodesHaveChilds || String.IsNullOrEmpty(dependentOf)) {
var parent = GetItemParentNode(item);
var itemPath = CommonUtils.GetAbsoluteFilePath(ProjectHome, item.EvaluatedInclude);
var existingChild = FindNodeByFullPath(itemPath);
if (existingChild != null) {
if (existingChild.IsLinkFile) {
// remove link node.
existingChild.Parent.RemoveChild(existingChild);
} else {
// we have duplicate entries, or this is a link file.
continue;
}
}
AddIndependentFileNode(item, parent);
} else {
// We will process dependent items later.
// Note that we use 2 lists as we want to remove elements from
// the collection as we loop through it
subitemsKeys.Add(item.EvaluatedInclude);
subitems.Add(item.EvaluatedInclude, item);
}
}
// Now process the dependent items.
if (this.CanFileNodesHaveChilds) {
ProcessDependentFileNodes(subitemsKeys, subitems);
}
}
private static bool IsVisibleItem(MSBuild.ProjectItem item) {
bool isVisibleItem = true;
string visible = item.GetMetadataValue(CommonConstants.Visible);
if ((item.IsImported && !String.Equals(visible, "true", StringComparison.OrdinalIgnoreCase)) ||
String.Equals(visible, "false", StringComparison.OrdinalIgnoreCase)) {
isVisibleItem = false;
}
return isVisibleItem;
}
/// <summary>
/// Processes dependent filenodes from list of subitems. Multi level supported, but not circular dependencies.
/// </summary>
/// <param name="subitemsKeys">List of sub item keys </param>
/// <param name="subitems"></param>
protected internal virtual void ProcessDependentFileNodes(IList<String> subitemsKeys, Dictionary<String, MSBuild.ProjectItem> subitems) {
if (subitemsKeys == null || subitems == null) {
return;
}
foreach (string key in subitemsKeys) {
// A previous pass could have removed the key so make sure it still needs to be added
if (!subitems.ContainsKey(key))
continue;
AddDependentFileNode(subitems, key);
}
}
/// <summary>
/// For flavored projects which implement IPersistXMLFragment, load the information now
/// </summary>
protected internal virtual void LoadNonBuildInformation() {
IPersistXMLFragment outerHierarchy = GetOuterInterface<IPersistXMLFragment>();
if (outerHierarchy != null) {
this.LoadXmlFragment(outerHierarchy, null, null);
}
}
/// <summary>
/// Used to sort nodes in the hierarchy.
/// </summary>
internal int CompareNodes(HierarchyNode node1, HierarchyNode node2) {
Debug.Assert(node1 != null);
Debug.Assert(node2 != null);
if (node1.SortPriority == node2.SortPriority) {
return String.Compare(node2.Caption, node1.Caption, true, CultureInfo.CurrentCulture);
} else {
return node2.SortPriority - node1.SortPriority;
}
}
protected abstract void InitializeCATIDs();
#endregion
#region non-virtual methods
internal void InstantiateItemsDraggedOrCutOrCopiedList() {
itemsDraggedOrCutOrCopied = new List<HierarchyNode>();
}
/// <summary>
/// Overloaded method. Invokes MSBuild using the default configuration and does without logging on the output window pane.
/// </summary>
public MSBuildResult Build(string target) {
Site.GetUIThread().MustBeCalledFromUIThread();
return this.Build(String.Empty, target);
}
/// <summary>
/// This is called from the main thread before the background build starts.
/// cleanBuild is not part of the vsopts, but passed down as the callpath is differently
/// PrepareBuild mainly creates directories and cleans house if cleanBuild is true
/// </summary>
public virtual void PrepareBuild(string config, bool cleanBuild) {
Site.GetUIThread().MustBeCalledFromUIThread();
try {
SetConfiguration(config);
string outputPath = Path.GetDirectoryName(GetProjectProperty("OutputPath"));
PackageUtilities.EnsureOutputPath(outputPath);
} finally {
SetCurrentConfiguration();
}
}
/// <summary>
/// Do the build by invoking msbuild
/// </summary>
public virtual MSBuildResult Build(string config, string target) {
Site.GetUIThread().MustBeCalledFromUIThread();
lock (ProjectNode.BuildLock) {
IVsOutputWindowPane output = null;
var outputWindow = (IVsOutputWindow)GetService(typeof(SVsOutputWindow));
if (outputWindow != null &&
ErrorHandler.Failed(outputWindow.GetPane(VSConstants.GUID_BuildOutputWindowPane, out output))) {
outputWindow.CreatePane(VSConstants.GUID_BuildOutputWindowPane, "Build", 1, 1);
outputWindow.GetPane(VSConstants.GUID_BuildOutputWindowPane, out output);
}
bool engineLogOnlyCritical = this.BuildPrelude(output);
MSBuildResult result = MSBuildResult.Failed;
try {
SetBuildConfigurationProperties(config);
result = InvokeMsBuild(target);
} finally {
// Unless someone specifically request to use an output window pane, we should not output to it
if (null != output) {
SetOutputLogger(null);
BuildEngine.OnlyLogCriticalEvents = engineLogOnlyCritical;
}
}
return result;
}
}
/// <summary>
/// Get value of Project property
/// </summary>
/// <param name="propertyName">Name of Property to retrieve</param>
/// <returns>Value of property</returns>
public string GetProjectProperty(string propertyName) {
return this.GetProjectProperty(propertyName, true);
}
/// <summary>
/// Get Node from ItemID.
/// </summary>
/// <param name="itemId">ItemID for the requested node</param>
/// <returns>Node if found</returns>
public HierarchyNode NodeFromItemId(uint itemId) {
if (VSConstants.VSITEMID_ROOT == itemId) {
return this;
} else if (VSConstants.VSITEMID_NIL == itemId) {
return null;
} else if (VSConstants.VSITEMID_SELECTION == itemId) {
throw new NotImplementedException();
}
return (HierarchyNode)this.ItemIdMap[itemId];
}
/// <summary>
/// This method return new project element, and add new MSBuild item to the project/build hierarchy
/// </summary>
/// <param name="file">file name</param>
/// <param name="itemType">MSBuild item type</param>
/// <returns>new project element</returns>
public MsBuildProjectElement CreateMsBuildFileItem(string file, string itemType) {
return new MsBuildProjectElement(this, file, itemType);
}
/// <summary>
/// This method returns new project element based on existing MSBuild item. It does not modify/add project/build hierarchy at all.
/// </summary>
/// <param name="item">MSBuild item instance</param>
/// <returns>wrapping project element</returns>
public MsBuildProjectElement GetProjectElement(MSBuild.ProjectItem item) {
return new MsBuildProjectElement(this, item);
}
/// <summary>
/// Create FolderNode from Path
/// </summary>
/// <param name="path">Path to folder</param>
/// <returns>FolderNode created that can be added to the hierarchy</returns>
protected internal FolderNode CreateFolderNode(string path) {
ProjectElement item = this.AddFolderToMsBuild(path);
FolderNode folderNode = CreateFolderNode(item);
return folderNode;
}
internal bool QueryEditFiles(bool suppressUI, params string[] files) {
bool result = true;
if (this.disableQueryEdit) {
return true;
} else {
IVsQueryEditQuerySave2 queryEditQuerySave = this.GetService(typeof(SVsQueryEditQuerySave)) as IVsQueryEditQuerySave2;
if (queryEditQuerySave != null) {
tagVSQueryEditFlags qef = tagVSQueryEditFlags.QEF_AllowInMemoryEdits;
if (suppressUI)
qef |= tagVSQueryEditFlags.QEF_SilentMode;
// If we are debugging, we want to prevent our project from being reloaded. To
// do this, we pass the QEF_NoReload flag
if (!Utilities.IsVisualStudioInDesignMode(this.Site))
qef |= tagVSQueryEditFlags.QEF_NoReload;
uint verdict;
uint moreInfo;
uint[] flags = new uint[files.Length];
VSQEQS_FILE_ATTRIBUTE_DATA[] attributes = new VSQEQS_FILE_ATTRIBUTE_DATA[files.Length];
int hr = queryEditQuerySave.QueryEditFiles(
(uint)qef,
files.Length, // 1 file
files, // array of files
flags, // no per file flags
attributes, // no per file file attributes
out verdict,
out moreInfo // ignore additional results
);
tagVSQueryEditResult qer = (tagVSQueryEditResult)verdict;
if (ErrorHandler.Failed(hr) || (qer != tagVSQueryEditResult.QER_EditOK)) {
if (!suppressUI && !Utilities.IsInAutomationFunction(this.Site)) {
string message = files.Length == 1 ?
SR.GetString(SR.CancelQueryEdit, files[0]) :
SR.GetString(SR.CancelQueryEditMultiple);
string title = string.Empty;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
VsShellUtilities.ShowMessageBox(this.Site, title, message, icon, buttons, defaultButton);
}
result = false;
}
}
}
return result;
}
/// <summary>
/// Verify if the file can be written to.
/// Return false if the file is read only and/or not checked out
/// and the user did not give permission to change it.
/// Note that exact behavior can also be affected based on the SCC
/// settings under Tools->Options.
/// </summary>
internal bool QueryEditProjectFile(bool suppressUI) {
return QueryEditFiles(suppressUI, filename);
}
internal bool QueryFolderAdd(HierarchyNode targetFolder, string path) {
if (!disableQueryEdit) {
var queryTrack = this.GetService(typeof(SVsTrackProjectDocuments)) as IVsTrackProjectDocuments2;
if (queryTrack != null) {
VSQUERYADDDIRECTORYRESULTS[] res = new VSQUERYADDDIRECTORYRESULTS[1];
ErrorHandler.ThrowOnFailure(
queryTrack.OnQueryAddDirectories(
GetOuterInterface<IVsProject>(),
1,
new[] { CommonUtils.GetAbsoluteFilePath(GetBaseDirectoryForAddingFiles(targetFolder), Path.GetFileName(path)) },
new[] { VSQUERYADDDIRECTORYFLAGS.VSQUERYADDDIRECTORYFLAGS_padding },
res,
res
)
);
if (res[0] == VSQUERYADDDIRECTORYRESULTS.VSQUERYADDDIRECTORYRESULTS_AddNotOK) {
return false;
}
}
}
return true;
}
internal bool QueryFolderRemove(HierarchyNode targetFolder, string path) {
if (!disableQueryEdit) {
var queryTrack = this.GetService(typeof(SVsTrackProjectDocuments)) as IVsTrackProjectDocuments2;
if (queryTrack != null) {
VSQUERYREMOVEDIRECTORYRESULTS[] res = new VSQUERYREMOVEDIRECTORYRESULTS[1];
ErrorHandler.ThrowOnFailure(
queryTrack.OnQueryRemoveDirectories(
GetOuterInterface<IVsProject>(),
1,
new[] { CommonUtils.GetAbsoluteFilePath(GetBaseDirectoryForAddingFiles(targetFolder), Path.GetFileName(path)) },
new[] { VSQUERYREMOVEDIRECTORYFLAGS.VSQUERYREMOVEDIRECTORYFLAGS_padding },
res,
res
)
);
if (res[0] == VSQUERYREMOVEDIRECTORYRESULTS.VSQUERYREMOVEDIRECTORYRESULTS_RemoveNotOK) {
return false;
}
}
}
return true;
}
/// <summary>
/// Given a node determines what is the directory that can accept files.
/// If the node is a FoldeNode than it is the Url of the Folder.
/// If the node is a ProjectNode it is the project folder.
/// Otherwise (such as FileNode subitem) it delegate the resolution to the parent node.
/// </summary>
internal string GetBaseDirectoryForAddingFiles(HierarchyNode nodeToAddFile) {
string baseDir = String.Empty;
if (nodeToAddFile is FolderNode) {
baseDir = nodeToAddFile.Url;
} else if (nodeToAddFile is ProjectNode) {
baseDir = this.ProjectHome;
} else if (nodeToAddFile != null) {
baseDir = GetBaseDirectoryForAddingFiles(nodeToAddFile.Parent);
}
return baseDir;
}
/// <summary>
/// For internal use only.
/// This creates a copy of an existing configuration and add it to the project.
/// Caller should change the condition on the PropertyGroup.
/// If derived class want to accomplish this, they should call ConfigProvider.AddCfgsOfCfgName()
/// It is expected that in the future MSBuild will have support for this so we don't have to
/// do it manually.
/// </summary>
/// <param name="group">PropertyGroup to clone</param>
/// <returns></returns>
internal MSBuildConstruction.ProjectPropertyGroupElement ClonePropertyGroup(MSBuildConstruction.ProjectPropertyGroupElement group) {
// Create a new (empty) PropertyGroup
MSBuildConstruction.ProjectPropertyGroupElement newPropertyGroup = this.buildProject.Xml.AddPropertyGroup();
// Now copy everything from the group we are trying to clone to the group we are creating
if (!String.IsNullOrEmpty(group.Condition))
newPropertyGroup.Condition = group.Condition;
foreach (MSBuildConstruction.ProjectPropertyElement prop in group.Properties) {
MSBuildConstruction.ProjectPropertyElement newProperty = newPropertyGroup.AddProperty(prop.Name, prop.Value);
if (!String.IsNullOrEmpty(prop.Condition))
newProperty.Condition = prop.Condition;
}
return newPropertyGroup;
}
/// <summary>
/// Get the project extensions
/// </summary>
/// <returns></returns>
internal MSBuildConstruction.ProjectExtensionsElement GetProjectExtensions() {
var extensionsElement = this.buildProject.Xml.ChildrenReversed.OfType<MSBuildConstruction.ProjectExtensionsElement>().FirstOrDefault();
if (extensionsElement == null) {
extensionsElement = this.buildProject.Xml.CreateProjectExtensionsElement();
this.buildProject.Xml.AppendChild(extensionsElement);
}
return extensionsElement;
}
/// <summary>
/// Set the xmlText as a project extension element with the id passed.
/// </summary>
/// <param name="id">The id of the project extension element.</param>
/// <param name="xmlText">The value to set for a project extension.</param>
internal void SetProjectExtensions(string id, string xmlText) {
MSBuildConstruction.ProjectExtensionsElement element = this.GetProjectExtensions();
// If it doesn't already have a value and we're asked to set it to
// nothing, don't do anything. Same as old OM. Keeps project neat.
if (element == null) {
if (xmlText.Length == 0) {
return;
}
element = this.buildProject.Xml.CreateProjectExtensionsElement();
this.buildProject.Xml.AppendChild(element);
}
element[id] = xmlText;
}
/// <summary>
/// Register the project with the Scc manager.
/// </summary>
protected void RegisterSccProject() {
if (this.isRegisteredWithScc || String.IsNullOrEmpty(this.sccProjectName)) {
return;
}
IVsSccManager2 sccManager = this.Site.GetService(typeof(SVsSccManager)) as IVsSccManager2;
if (sccManager != null) {
ErrorHandler.ThrowOnFailure(sccManager.RegisterSccProject(this, this.sccProjectName, this.sccAuxPath, this.sccLocalPath, this.sccProvider));
this.isRegisteredWithScc = true;
}
}
/// <summary>
/// Unregisters us from the SCC manager
/// </summary>
protected void UnRegisterProject() {
if (!this.isRegisteredWithScc) {
return;
}
IVsSccManager2 sccManager = this.Site.GetService(typeof(SVsSccManager)) as IVsSccManager2;
if (sccManager != null) {
ErrorHandler.ThrowOnFailure(sccManager.UnregisterSccProject(this));
this.isRegisteredWithScc = false;
}
}
/// <summary>
/// Get the CATID corresponding to the specified type.
/// </summary>
/// <param name="type">Type of the object for which you want the CATID</param>
/// <returns>CATID</returns>
protected internal Guid GetCATIDForType(Type type) {
Utilities.ArgumentNotNull("type", type);
if (catidMapping == null) {
catidMapping = new Dictionary<Type, Guid>();
InitializeCATIDs();
}
Guid result;
if (catidMapping.TryGetValue(type, out result)) {
return result;
}
// If you get here and you want your object to be extensible, then add a call to AddCATIDMapping() in your project constructor
return Guid.Empty;
}
/// <summary>
/// This is used to specify a CATID corresponding to a BrowseObject or an ExtObject.
/// The CATID can be any GUID you choose. For types which are your owns, you could use
/// their type GUID, while for other types (such as those provided in the MPF) you should
/// provide a different GUID.
/// </summary>
/// <param name="type">Type of the extensible object</param>
/// <param name="catid">GUID that extender can use to uniquely identify your object type</param>
protected void AddCATIDMapping(Type type, Guid catid) {
if (catidMapping == null) {
catidMapping = new Dictionary<Type, Guid>();
InitializeCATIDs();
}
catidMapping.Add(type, catid);
}
/// <summary>
/// Initialize an object with an XML fragment.
/// </summary>
/// <param name="iPersistXMLFragment">Object that support being initialized with an XML fragment</param>
/// <param name="configName">Name of the configuration being initialized, null if it is the project</param>
/// <param name="platformName">Name of the platform being initialized, null is ok</param>
protected internal void LoadXmlFragment(IPersistXMLFragment persistXmlFragment, string configName, string platformName) {
Utilities.ArgumentNotNull("persistXmlFragment", persistXmlFragment);
if (xmlFragments == null) {
// Retrieve the xml fragments from MSBuild
xmlFragments = new XmlDocument();
string fragments = GetProjectExtensions()[ProjectFileConstants.VisualStudio];
fragments = String.Format(CultureInfo.InvariantCulture, "<root>{0}</root>", fragments);
xmlFragments.LoadXml(fragments);
}
// We need to loop through all the flavors
string flavorsGuid;
ErrorHandler.ThrowOnFailure(((IVsAggregatableProject)this).GetAggregateProjectTypeGuids(out flavorsGuid));
foreach (Guid flavor in Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(flavorsGuid)) {
// Look for a matching fragment
string flavorGuidString = flavor.ToString("B");
string fragment = null;
XmlNode node = null;
foreach (XmlNode child in xmlFragments.FirstChild.ChildNodes) {
if (child.Attributes.Count > 0) {
string guid = String.Empty;
string configuration = String.Empty;
string platform = String.Empty;
if (child.Attributes[ProjectFileConstants.Guid] != null)
guid = child.Attributes[ProjectFileConstants.Guid].Value;
if (child.Attributes[ProjectFileConstants.Configuration] != null)
configuration = child.Attributes[ProjectFileConstants.Configuration].Value;
if (child.Attributes[ProjectFileConstants.Platform] != null)
platform = child.Attributes[ProjectFileConstants.Platform].Value;
if (String.Compare(child.Name, ProjectFileConstants.FlavorProperties, StringComparison.OrdinalIgnoreCase) == 0
&& String.Compare(guid, flavorGuidString, StringComparison.OrdinalIgnoreCase) == 0
&& ((String.IsNullOrEmpty(configName) && String.IsNullOrEmpty(configuration))
|| (String.Compare(configuration, configName, StringComparison.OrdinalIgnoreCase) == 0))
&& ((String.IsNullOrEmpty(platformName) && String.IsNullOrEmpty(platform))
|| (String.Compare(platform, platformName, StringComparison.OrdinalIgnoreCase) == 0))) {
// we found the matching fragment
fragment = child.InnerXml;
node = child;
break;
}
}
}
Guid flavorGuid = flavor;
if (String.IsNullOrEmpty(fragment)) {
// the fragment was not found so init with default values
ErrorHandler.ThrowOnFailure(persistXmlFragment.InitNew(ref flavorGuid, (uint)_PersistStorageType.PST_PROJECT_FILE));
// While we don't yet support user files, our flavors might, so we will store that in the project file until then
// TODO: Refactor this code when we support user files
ErrorHandler.ThrowOnFailure(persistXmlFragment.InitNew(ref flavorGuid, (uint)_PersistStorageType.PST_USER_FILE));
} else {
ErrorHandler.ThrowOnFailure(persistXmlFragment.Load(ref flavorGuid, (uint)_PersistStorageType.PST_PROJECT_FILE, fragment));
// While we don't yet support user files, our flavors might, so we will store that in the project file until then
// TODO: Refactor this code when we support user files
if (node.NextSibling != null && node.NextSibling.Attributes[ProjectFileConstants.User] != null)
ErrorHandler.ThrowOnFailure(persistXmlFragment.Load(ref flavorGuid, (uint)_PersistStorageType.PST_USER_FILE, node.NextSibling.InnerXml));
}
}
}
/// <summary>
/// Retrieve all XML fragments that need to be saved from the flavors and store the information in msbuild.
/// </summary>
protected void PersistXMLFragments() {
if (IsFlavorDirty()) {
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("ROOT");
// We will need the list of configuration inside the loop, so get it before entering the loop
uint[] count = new uint[1];
IVsCfg[] configs = null;
int hr = this.ConfigProvider.GetCfgs(0, null, count, null);
if (ErrorHandler.Succeeded(hr) && count[0] > 0) {
configs = new IVsCfg[count[0]];
hr = this.ConfigProvider.GetCfgs((uint)configs.Length, configs, count, null);
if (ErrorHandler.Failed(hr))
count[0] = 0;
}
if (count[0] == 0)
configs = new IVsCfg[0];
// We need to loop through all the flavors
string flavorsGuid;
ErrorHandler.ThrowOnFailure(((IVsAggregatableProject)this).GetAggregateProjectTypeGuids(out flavorsGuid));
foreach (Guid flavor in Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(flavorsGuid)) {
IPersistXMLFragment outerHierarchy = GetOuterInterface<IPersistXMLFragment>();
// First check the project
if (outerHierarchy != null) {
// Retrieve the XML fragment
string fragment = string.Empty;
Guid flavorGuid = flavor;
ErrorHandler.ThrowOnFailure((outerHierarchy).Save(ref flavorGuid, (uint)_PersistStorageType.PST_PROJECT_FILE, out fragment, 1));
if (!String.IsNullOrEmpty(fragment)) {
// Add the fragment to our XML
WrapXmlFragment(doc, root, flavor, null, null, fragment);
}
// While we don't yet support user files, our flavors might, so we will store that in the project file until then
// TODO: Refactor this code when we support user files
fragment = String.Empty;
ErrorHandler.ThrowOnFailure((outerHierarchy).Save(ref flavorGuid, (uint)_PersistStorageType.PST_USER_FILE, out fragment, 1));
if (!String.IsNullOrEmpty(fragment)) {
// Add the fragment to our XML
XmlElement node = WrapXmlFragment(doc, root, flavor, null, null, fragment);
node.Attributes.Append(doc.CreateAttribute(ProjectFileConstants.User));
}
}
// Then look at the configurations
foreach (IVsCfg config in configs) {
// Get the fragment for this flavor/config pair
string fragment;
ErrorHandler.ThrowOnFailure(((ProjectConfig)config).GetXmlFragment(flavor, _PersistStorageType.PST_PROJECT_FILE, out fragment));
if (!String.IsNullOrEmpty(fragment)) {
WrapXmlFragment(doc, root, flavor, ((ProjectConfig)config).ConfigName, ((ProjectConfig)config).PlatformName, fragment);
}
}
}
if (root.ChildNodes != null && root.ChildNodes.Count > 0) {
// Save our XML (this is only the non-build information for each flavor) in msbuild
SetProjectExtensions(ProjectFileConstants.VisualStudio, root.InnerXml.ToString());
}
}
}
#if DEV14_OR_LATER
[Obsolete("Use ImageMonikers instead")]
#endif
internal int GetIconIndex(ImageName name) {
return (int)name;
}
#if DEV14_OR_LATER
[Obsolete("Use ImageMonikers instead")]
#endif
internal IntPtr GetIconHandleByName(ImageName name) {
return ImageHandler.GetIconHandle(GetIconIndex(name));
}
internal Dictionary<string, string> ParseCommandArgs(IntPtr vaIn, Guid cmdGroup, uint cmdId) {
var switches = QueryCommandArguments(cmdGroup, cmdId, CommandOrigin.UiHierarchy);
if (string.IsNullOrEmpty(switches)) {
return null;
}
return ParseCommandArgs(vaIn, switches);
}
internal Dictionary<string, string> ParseCommandArgs(IntPtr vaIn, string switches) {
string args;
if (vaIn == IntPtr.Zero || string.IsNullOrEmpty(args = Marshal.GetObjectForNativeVariant(vaIn) as string)) {
return null;
}
var parse = Site.GetService(typeof(SVsParseCommandLine)) as IVsParseCommandLine;
if (ErrorHandler.Failed(parse.ParseCommandTail(args, -1))) {
return null;
}
parse.EvaluateSwitches(switches);
var res = new Dictionary<string, string>();
int i = -1;
foreach (var sw in switches.Split(' ')) {
i += 1;
var key = sw;
int comma = key.IndexOf(',');
if (comma > 0) {
key = key.Remove(comma);
}
string value;
int hr;
switch (hr = parse.IsSwitchPresent(i)) {
case VSConstants.S_OK:
ErrorHandler.ThrowOnFailure(parse.GetSwitchValue(i, out value));
res[key] = value;
break;
case VSConstants.S_FALSE:
break;
default:
ErrorHandler.ThrowOnFailure(hr);
break;
}
}
i = 0;
int count;
ErrorHandler.ThrowOnFailure(parse.GetParamCount(out count));
for (i = 0; i < count; ++i) {
string key = i.ToString(), value;
ErrorHandler.ThrowOnFailure(parse.GetParam(i, out value));
res[key] = value;
}
return res;
}
#endregion
#region IVsGetCfgProvider Members
//=================================================================================
public virtual int GetCfgProvider(out IVsCfgProvider p) {
// Be sure to call the property here since that is doing a polymorhic ProjectConfig creation.
p = this.ConfigProvider;
return (p == null ? VSConstants.E_NOTIMPL : VSConstants.S_OK);
}
#endregion
#region IPersist Members
public int GetClassID(out Guid clsid) {
clsid = this.ProjectGuid;
return VSConstants.S_OK;
}
#endregion
#region IPersistFileFormat Members
int IPersistFileFormat.GetClassID(out Guid clsid) {
clsid = this.ProjectGuid;
return VSConstants.S_OK;
}
public virtual int GetCurFile(out string name, out uint formatIndex) {
name = this.filename;
formatIndex = 0;
return VSConstants.S_OK;
}
public virtual int GetFormatList(out string formatlist) {
formatlist = String.Empty;
return VSConstants.S_OK;
}
public virtual int InitNew(uint formatIndex) {
return VSConstants.S_OK;
}
public virtual int IsDirty(out int isDirty) {
if (BuildProject.Xml.HasUnsavedChanges || IsProjectFileDirty || IsFlavorDirty()) {
isDirty = 1;
} else {
isDirty = 0;
}
return VSConstants.S_OK;
}
/// <summary>
/// Get the outer IVsHierarchy implementation.
/// This is used for scenario where a flavor may be modifying the behavior
/// </summary>
internal IVsHierarchy GetOuterHierarchy() {
IVsHierarchy hierarchy = null;
// The hierarchy of a node is its project node hierarchy
IntPtr projectUnknown = Marshal.GetIUnknownForObject(this);
try {
hierarchy = (IVsHierarchy)Marshal.GetTypedObjectForIUnknown(projectUnknown, typeof(IVsHierarchy));
} finally {
if (projectUnknown != IntPtr.Zero) {
Marshal.Release(projectUnknown);
}
}
return hierarchy;
}
internal T GetOuterInterface<T>() where T : class {
return GetOuterHierarchy() as T;
}
private bool IsFlavorDirty() {
int isDirty = 0;
// See if one of our flavor consider us dirty
IPersistXMLFragment outerHierarchy = GetOuterInterface<IPersistXMLFragment>();
if (outerHierarchy != null) {
// First check the project
ErrorHandler.ThrowOnFailure(outerHierarchy.IsFragmentDirty((uint)_PersistStorageType.PST_PROJECT_FILE, out isDirty));
// While we don't yet support user files, our flavors might, so we will store that in the project file until then
// TODO: Refactor this code when we support user files
if (isDirty == 0)
ErrorHandler.ThrowOnFailure(outerHierarchy.IsFragmentDirty((uint)_PersistStorageType.PST_USER_FILE, out isDirty));
}
if (isDirty == 0) {
// Then look at the configurations
uint[] count = new uint[1];
int hr = this.ConfigProvider.GetCfgs(0, null, count, null);
if (ErrorHandler.Succeeded(hr) && count[0] > 0) {
// We need to loop through the configurations
IVsCfg[] configs = new IVsCfg[count[0]];
hr = this.ConfigProvider.GetCfgs((uint)configs.Length, configs, count, null);
Debug.Assert(ErrorHandler.Succeeded(hr), "failed to retrieve configurations");
foreach (IVsCfg config in configs) {
isDirty = ((ProjectConfig)config).IsFlavorDirty(_PersistStorageType.PST_PROJECT_FILE);
if (isDirty != 0)
break;
}
}
}
return isDirty != 0;
}
int IPersistFileFormat.Load(string fileName, uint mode, int readOnly) {
// This isn't how projects are loaded, C#, VB, and CPS all fail this call
return VSConstants.E_NOTIMPL;
}
public virtual int Save(string fileToBeSaved, int remember, uint formatIndex) {
// The file name can be null. Then try to use the Url.
string tempFileToBeSaved = fileToBeSaved;
if (String.IsNullOrEmpty(tempFileToBeSaved) && !String.IsNullOrEmpty(this.Url)) {
tempFileToBeSaved = this.Url;
}
if (String.IsNullOrEmpty(tempFileToBeSaved)) {
throw new ArgumentException(SR.GetString(SR.InvalidParameter), "fileToBeSaved");
}
int setProjectFileDirtyAfterSave = 0;
if (remember == 0) {
ErrorHandler.ThrowOnFailure(IsDirty(out setProjectFileDirtyAfterSave));
}
// Update the project with the latest flavor data (if needed)
PersistXMLFragments();
int result = VSConstants.S_OK;
bool saveAs = true;
if (CommonUtils.IsSamePath(tempFileToBeSaved, this.filename)) {
saveAs = false;
}
if (!saveAs) {
SuspendFileChanges fileChanges = new SuspendFileChanges(this.Site, this.filename);
fileChanges.Suspend();
try {
// Ensure the directory exist
string saveFolder = Path.GetDirectoryName(tempFileToBeSaved);
if (!Directory.Exists(saveFolder))
Directory.CreateDirectory(saveFolder);
// Save the project
SaveMSBuildProjectFile(tempFileToBeSaved);
} finally {
fileChanges.Resume();
}
} else {
result = this.SaveAs(tempFileToBeSaved);
if (result != VSConstants.OLE_E_PROMPTSAVECANCELLED) {
ErrorHandler.ThrowOnFailure(result);
}
}
if (setProjectFileDirtyAfterSave != 0) {
isDirty = true;
}
return result;
}
protected virtual void SaveMSBuildProjectFile(string filename) {
buildProject.Save(filename);
isDirty = false;
}
public virtual int SaveCompleted(string filename) {
// TODO: turn file watcher back on.
return VSConstants.S_OK;
}
#endregion
#region IVsProject3 Members
/// <summary>
/// Callback from the additem dialog. Deals with adding new and existing items
/// </summary>
public virtual int GetMkDocument(uint itemId, out string mkDoc) {
mkDoc = null;
if (itemId == VSConstants.VSITEMID_SELECTION) {
return VSConstants.E_UNEXPECTED;
}
HierarchyNode n = this.NodeFromItemId(itemId);
if (n == null) {
return VSConstants.E_INVALIDARG;
}
mkDoc = n.GetMkDocument();
if (String.IsNullOrEmpty(mkDoc)) {
return VSConstants.E_FAIL;
}
return VSConstants.S_OK;
}
public virtual int AddItem(uint itemIdLoc, VSADDITEMOPERATION op, string itemName, uint filesToOpen, string[] files, IntPtr dlgOwner, VSADDRESULT[] result) {
Guid empty = Guid.Empty;
return AddItemWithSpecific(
itemIdLoc,
op,
itemName,
filesToOpen,
files,
dlgOwner,
op == VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE ? (uint)__VSSPECIFICEDITORFLAGS.VSSPECIFICEDITOR_DoOpen : 0,
ref empty,
null,
ref empty,
result);
}
/// <summary>
/// Creates new items in a project, adds existing files to a project, or causes Add Item wizards to be run
/// </summary>
/// <param name="itemIdLoc"></param>
/// <param name="op"></param>
/// <param name="itemName"></param>
/// <param name="filesToOpen"></param>
/// <param name="files">Array of file names.
/// If dwAddItemOperation is VSADDITEMOP_CLONEFILE the first item in the array is the name of the file to clone.
/// If dwAddItemOperation is VSADDITEMOP_OPENDIRECTORY, the first item in the array is the directory to open.
/// If dwAddItemOperation is VSADDITEMOP_RUNWIZARD, the first item is the name of the wizard to run,
/// and the second item is the file name the user supplied (same as itemName).</param>
/// <param name="dlgOwner"></param>
/// <param name="editorFlags"></param>
/// <param name="editorType"></param>
/// <param name="physicalView"></param>
/// <param name="logicalView"></param>
/// <param name="result"></param>
/// <returns>S_OK if it succeeds </returns>
/// <remarks>The result array is initalized to failure.</remarks>
public virtual int AddItemWithSpecific(uint itemIdLoc, VSADDITEMOPERATION op, string itemName, uint filesToOpen, string[] files, IntPtr dlgOwner, uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, VSADDRESULT[] result) {
return AddItemWithSpecificInternal(itemIdLoc, op, itemName, filesToOpen, files, dlgOwner, editorFlags, ref editorType, physicalView, ref logicalView, result);
}
// TODO: Refactor me into something sane
internal int AddItemWithSpecificInternal(uint itemIdLoc, VSADDITEMOPERATION op, string itemName, uint filesToOpen, string[] files, IntPtr dlgOwner, uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, VSADDRESULT[] result, bool? promptOverwrite = null) {
if (files == null || result == null || files.Length == 0 || result.Length == 0) {
return VSConstants.E_INVALIDARG;
}
// Locate the node to be the container node for the file(s) being added
// only projectnode or foldernode and file nodes are valid container nodes
// We need to locate the parent since the item wizard expects the parent to be passed.
HierarchyNode n = this.NodeFromItemId(itemIdLoc);
if (n == null) {
return VSConstants.E_INVALIDARG;
}
while (!n.CanAddFiles && (!this.CanFileNodesHaveChilds || !(n is FileNode))) {
n = n.Parent;
}
Debug.Assert(n != null, "We should at this point have either a ProjectNode or FolderNode or a FileNode as a container for the new filenodes");
// handle link and runwizard operations at this point
bool isLink = false;
switch (op) {
case VSADDITEMOPERATION.VSADDITEMOP_LINKTOFILE:
// we do not support this right now
isLink = true;
break;
case VSADDITEMOPERATION.VSADDITEMOP_RUNWIZARD:
result[0] = this.RunWizard(n, itemName, files[0], dlgOwner);
return VSConstants.S_OK;
}
string[] actualFiles = new string[files.Length];
VSQUERYADDFILEFLAGS[] flags = this.GetQueryAddFileFlags(files);
string baseDir = this.GetBaseDirectoryForAddingFiles(n);
// If we did not get a directory for node that is the parent of the item then fail.
if (String.IsNullOrEmpty(baseDir)) {
return VSConstants.E_FAIL;
}
// Pre-calculates some paths that we can use when calling CanAddItems
List<string> filesToAdd = new List<string>();
foreach (var file in files) {
string fileName;
string newFileName = String.Empty;
switch (op) {
case VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE:
fileName = Path.GetFileName(itemName ?? file);
newFileName = CommonUtils.GetAbsoluteFilePath(baseDir, fileName);
break;
case VSADDITEMOPERATION.VSADDITEMOP_LINKTOFILE:
case VSADDITEMOPERATION.VSADDITEMOP_OPENFILE:
fileName = Path.GetFileName(file);
newFileName = CommonUtils.GetAbsoluteFilePath(baseDir, fileName);
if (isLink && CommonUtils.IsSubpathOf(ProjectHome, file)) {
// creating a link to a file that's actually in the project, it's not really a link.
isLink = false;
// If the file is not going to be added in its
// current path (GetDirectoryName(file) != baseDir),
// we need to update the filename and also update
// the destination node (n). Otherwise, we don't
// want to change the destination node (previous
// behavior) - just trust that our caller knows
// what they are doing. (Web Essentials relies on
// this.)
if (!CommonUtils.IsSameDirectory(baseDir, Path.GetDirectoryName(file))) {
newFileName = file;
n = this.CreateFolderNodes(Path.GetDirectoryName(file));
}
}
break;
}
filesToAdd.Add(newFileName);
}
// Ask tracker objects if we can add files
if (!this.tracker.CanAddItems(filesToAdd.ToArray(), flags)) {
// We were not allowed to add the files
return VSConstants.E_FAIL;
}
if (!this.QueryEditProjectFile(false)) {
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
// Add the files to the hierarchy
int actualFilesAddedIndex = 0;
var itemsToInvalidate = new List<HierarchyNode>();
for (int index = 0; index < filesToAdd.Count; index++) {
HierarchyNode child;
bool overwrite = false;
MsBuildProjectElement linkedFile = null;
string newFileName = filesToAdd[index];
string file = files[index];
result[0] = VSADDRESULT.ADDRESULT_Failure;
child = this.FindNodeByFullPath(newFileName);
if (child != null) {
// If the file to be added is an existing file part of the hierarchy then continue.
if (CommonUtils.IsSamePath(file, newFileName)) {
if (child.IsNonMemberItem) {
for (var node = child; node != null; node = node.Parent) {
itemsToInvalidate.Add(node);
// We want to include the first member item, so
// this test is not part of the loop condition.
if (!node.IsNonMemberItem) {
break;
}
}
// https://pytools.codeplex.com/workitem/1251
ErrorHandler.ThrowOnFailure(child.IncludeInProject(false));
}
result[0] = VSADDRESULT.ADDRESULT_Cancel;
continue;
} else if (isLink) {
string message = "There is already a file of the same name in this folder.";
string title = string.Empty;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_QUERY;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
VsShellUtilities.ShowMessageBox(this.Site, title, message, icon, buttons, defaultButton);
result[0] = VSADDRESULT.ADDRESULT_Cancel;
return (int)OleConstants.OLECMDERR_E_CANCELED;
} else {
int canOverWriteExistingItem = CanOverwriteExistingItem(file, newFileName, !child.IsNonMemberItem);
if (canOverWriteExistingItem == E_CANCEL_FILE_ADD) {
result[0] = VSADDRESULT.ADDRESULT_Cancel;
return (int)OleConstants.OLECMDERR_E_CANCELED;
} else if (canOverWriteExistingItem == (int)OleConstants.OLECMDERR_E_CANCELED) {
result[0] = VSADDRESULT.ADDRESULT_Cancel;
return canOverWriteExistingItem;
} else if (canOverWriteExistingItem == VSConstants.S_OK) {
overwrite = true;
} else {
return canOverWriteExistingItem;
}
}
} else {
if (isLink) {
child = this.FindNodeByFullPath(file);
if (child != null) {
string message = String.Format("There is already a link to '{0}'. A project cannot have more than one link to the same file.", file);
string title = string.Empty;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_QUERY;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
VsShellUtilities.ShowMessageBox(this.Site, title, message, icon, buttons, defaultButton);
result[0] = VSADDRESULT.ADDRESULT_Cancel;
return (int)OleConstants.OLECMDERR_E_CANCELED;
}
}
if (newFileName.Length >= NativeMethods.MAX_PATH) {
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
VsShellUtilities.ShowMessageBox(Site, FolderNode.PathTooLongMessage, null, icon, buttons, defaultButton);
result[0] = VSADDRESULT.ADDRESULT_Cancel;
return (int)OleConstants.OLECMDERR_E_CANCELED;
}
// we need to figure out where this file would be added and make sure there's
// not an existing link node at the same location
string filename = Path.GetFileName(newFileName);
var folder = this.FindNodeByFullPath(Path.GetDirectoryName(newFileName));
if (folder != null) {
if (folder.FindImmediateChildByName(filename) != null) {
string message = "There is already a file of the same name in this folder.";
string title = string.Empty;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_QUERY;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
VsShellUtilities.ShowMessageBox(this.Site, title, message, icon, buttons, defaultButton);
result[0] = VSADDRESULT.ADDRESULT_Cancel;
return (int)OleConstants.OLECMDERR_E_CANCELED;
}
}
}
// If the file to be added is not in the same path copy it.
if (!CommonUtils.IsSamePath(file, newFileName) || Directory.Exists(newFileName)) {
if (!overwrite && File.Exists(newFileName)) {
var existingChild = this.FindNodeByFullPath(file);
if (existingChild == null || !existingChild.IsLinkFile) {
string message = SR.GetString(SR.FileAlreadyExists, newFileName);
string title = string.Empty;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_QUERY;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_YESNO;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
if (isLink) {
message = "There is already a file of the same name in this folder.";
buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
}
int messageboxResult = VsShellUtilities.ShowMessageBox(this.Site, title, message, icon, buttons, defaultButton);
if (messageboxResult != NativeMethods.IDYES) {
result[0] = VSADDRESULT.ADDRESULT_Cancel;
return (int)OleConstants.OLECMDERR_E_CANCELED;
}
}
}
var updatingNode = this.FindNodeByFullPath(file);
if (updatingNode != null && updatingNode.IsLinkFile) {
// we just need to update the link to the new path.
linkedFile = updatingNode.ItemNode as MsBuildProjectElement;
} else if (Directory.Exists(file)) {
// http://pytools.codeplex.com/workitem/546
int hr = AddDirectory(result, n, file, promptOverwrite);
if (ErrorHandler.Failed(hr)) {
return hr;
}
result[0] = VSADDRESULT.ADDRESULT_Success;
continue;
} else if (!isLink) {
// Copy the file to the correct location.
// We will suppress the file change events to be triggered to this item, since we are going to copy over the existing file and thus we will trigger a file change event.
// We do not want the filechange event to ocur in this case, similar that we do not want a file change event to occur when saving a file.
IVsFileChangeEx fileChange = this.site.GetService(typeof(SVsFileChangeEx)) as IVsFileChangeEx;
Utilities.CheckNotNull(fileChange);
try {
ErrorHandler.ThrowOnFailure(fileChange.IgnoreFile(VSConstants.VSCOOKIE_NIL, newFileName, 1));
if (op == VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE) {
this.AddFileFromTemplate(file, newFileName);
} else {
PackageUtilities.CopyUrlToLocal(new Uri(file), newFileName);
// Reset RO attribute on file if present - for example, if source file was under TFS control and not checked out.
try {
var fileInfo = new FileInfo(newFileName);
if (fileInfo.Attributes.HasFlag(FileAttributes.ReadOnly)) {
fileInfo.Attributes &= ~FileAttributes.ReadOnly;
}
} catch (Exception ex) {
// Best-effort, but no big deal if this fails.
if (ex.IsCriticalException()) {
throw;
}
}
}
} finally {
ErrorHandler.ThrowOnFailure(fileChange.IgnoreFile(VSConstants.VSCOOKIE_NIL, newFileName, 0));
}
}
}
if (overwrite) {
if (child.IsNonMemberItem) {
ErrorHandler.ThrowOnFailure(child.IncludeInProject(false));
}
} else if (linkedFile != null || isLink) {
// files not moving, add the old name, and set the link.
var friendlyPath = CommonUtils.GetRelativeFilePath(ProjectHome, file);
FileNode newChild;
if (linkedFile == null) {
Debug.Assert(!CommonUtils.IsSubpathOf(ProjectHome, file), "Should have cleared isLink above for file in project dir");
newChild = CreateFileNode(file);
} else {
newChild = CreateFileNode(linkedFile);
}
newChild.SetIsLinkFile(true);
newChild.ItemNode.SetMetadata(ProjectFileConstants.Link, CommonUtils.CreateFriendlyFilePath(ProjectHome, newFileName));
n.AddChild(newChild);
DocumentManager.RenameDocument(site, file, file, n.ID);
LinkFileAdded(file);
} else {
//Add new filenode/dependentfilenode
this.AddNewFileNodeToHierarchy(n, newFileName);
}
result[0] = VSADDRESULT.ADDRESULT_Success;
actualFiles[actualFilesAddedIndex++] = newFileName;
}
// Notify listeners that items were appended.
if (actualFilesAddedIndex > 0)
OnItemsAppended(n);
foreach (var node in itemsToInvalidate.Where(node => node != null).Reverse()) {
OnInvalidateItems(node);
}
//Open files if this was requested through the editorFlags
bool openFiles = (editorFlags & (uint)__VSSPECIFICEDITORFLAGS.VSSPECIFICEDITOR_DoOpen) != 0;
if (openFiles && actualFiles.Length <= filesToOpen) {
for (int i = 0; i < filesToOpen; i++) {
if (!String.IsNullOrEmpty(actualFiles[i])) {
string name = actualFiles[i];
HierarchyNode child = this.FindNodeByFullPath(name);
Debug.Assert(child != null, "We should have been able to find the new element in the hierarchy");
if (child != null) {
IVsWindowFrame frame;
if (editorType == Guid.Empty) {
Guid view = child.DefaultOpensWithDesignView ? VSConstants.LOGVIEWID.Designer_guid : Guid.Empty;
ErrorHandler.ThrowOnFailure(this.OpenItem(child.ID, ref view, IntPtr.Zero, out frame));
} else {
ErrorHandler.ThrowOnFailure(this.OpenItemWithSpecific(child.ID, editorFlags, ref editorType, physicalView, ref logicalView, IntPtr.Zero, out frame));
}
// Show the window frame in the UI and make it the active window
if (frame != null) {
ErrorHandler.ThrowOnFailure(frame.Show());
}
}
}
}
}
return VSConstants.S_OK;
}
/// <summary>
/// Adds a folder into the project recursing and adding any sub-files and sub-directories.
///
/// The user can be prompted to overwrite the existing files if the folder already exists
/// in the project. They will be initially prompted to overwrite - if they answer no
/// we'll set promptOverwrite to false and when we recurse we won't prompt. If they say
/// yes then we'll set it to true and we will prompt for individual files.
/// </summary>
private int AddDirectory(VSADDRESULT[] result, HierarchyNode n, string file, bool? promptOverwrite) {
// need to recursively add all of the directory contents
HierarchyNode targetFolder = n.FindImmediateChildByName(Path.GetFileName(file));
if (targetFolder == null) {
var fullPath = Path.Combine(GetBaseDirectoryForAddingFiles(n), Path.GetFileName(file));
Directory.CreateDirectory(fullPath);
var newChild = CreateFolderNode(fullPath);
n.AddChild(newChild);
targetFolder = newChild;
} else if (targetFolder.IsNonMemberItem) {
int hr = targetFolder.IncludeInProject(true);
if (ErrorHandler.Succeeded(hr)) {
OnInvalidateItems(targetFolder.Parent);
}
return hr;
} else if (promptOverwrite == null) {
var res = MessageBox.Show(
String.Format(
@"This folder already contains a folder called '{0}'.
If the files in the existing folder have the same names as files in the folder you are copying, do you want to replace the existing files?", Path.GetFileName(file)),
"Merge Folders",
MessageBoxButtons.YesNoCancel
);
// yes means prompt for each file
// no means don't prompt for any of the files
// cancel means forget what I'm doing
switch (res) {
case DialogResult.Cancel:
result[0] = VSADDRESULT.ADDRESULT_Cancel;
return (int)OleConstants.OLECMDERR_E_CANCELED;
case DialogResult.No:
promptOverwrite = false;
break;
case DialogResult.Yes:
promptOverwrite = true;
break;
}
}
Guid empty = Guid.Empty;
// add the files...
var dirFiles = Directory.GetFiles(file);
if (dirFiles.Length > 0) {
var subRes = AddItemWithSpecificInternal(
targetFolder.ID,
VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE,
null,
(uint)dirFiles.Length,
dirFiles,
IntPtr.Zero,
0,
ref empty,
null,
ref empty,
result,
promptOverwrite: promptOverwrite
);
if (ErrorHandler.Failed(subRes)) {
return subRes;
}
}
// add any subdirectories...
var subDirs = Directory.GetDirectories(file);
if (subDirs.Length > 0) {
return AddItemWithSpecificInternal(
targetFolder.ID,
VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE,
null,
(uint)subDirs.Length,
subDirs,
IntPtr.Zero,
0,
ref empty,
null,
ref empty,
result,
promptOverwrite: promptOverwrite
);
}
return VSConstants.S_OK;
}
protected virtual void LinkFileAdded(string filename) {
}
private static string GetIncrementedFileName(string newFileName, int count) {
return CommonUtils.GetAbsoluteFilePath(Path.GetDirectoryName(newFileName), Path.GetFileNameWithoutExtension(newFileName) + " - Copy (" + count + ")" + Path.GetExtension(newFileName));
}
/// <summary>
/// for now used by add folder. Called on the ROOT, as only the project should need
/// to implement this.
/// for folders, called with parent folder, blank extension and blank suggested root
/// </summary>
public virtual int GenerateUniqueItemName(uint itemIdLoc, string ext, string suggestedRoot, out string itemName) {
string root = string.IsNullOrEmpty(suggestedRoot) ? "NewFolder" : suggestedRoot.Trim();
string extToUse = string.IsNullOrEmpty(ext) ? "" : ext.Trim();
itemName = string.Empty;
// Find the folder or project the item is being added to.
HierarchyNode parent = NodeFromItemId(itemIdLoc);
while (parent != null && !parent.CanAddFiles) {
parent = parent.Parent;
}
if (parent == null) {
return VSConstants.E_FAIL;
}
var parentProject = parent as ProjectNode;
var destDirectory = parentProject != null ? parentProject.ProjectHome : parent.Url;
for (int count = 1; count < int.MaxValue; ++count) {
var candidate = string.Format(
CultureInfo.CurrentCulture,
"{0}{1}{2}",
root,
count,
extToUse
);
var candidatePath = CommonUtils.GetAbsoluteFilePath(destDirectory, candidate);
if (File.Exists(candidatePath) || Directory.Exists(candidatePath)) {
// Cannot create a file or a directory when one exists with
// the same name.
continue;
}
if (parent.AllChildren.Any(n => candidate == n.GetItemName())) {
// Cannot create a node if one exists with the same name.
continue;
}
itemName = candidate;
return VSConstants.S_OK;
}
return VSConstants.E_FAIL;
}
public virtual int GetItemContext(uint itemId, out Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp) {
// the as cast isn't necessary, but makes it obvious via Find all refs how this is being used
psp = this.NodeFromItemId(itemId) as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
return VSConstants.S_OK;
}
public virtual int IsDocumentInProject(string mkDoc, out int found, VSDOCUMENTPRIORITY[] pri, out uint itemId) {
if (pri != null && pri.Length >= 1) {
pri[0] = VSDOCUMENTPRIORITY.DP_Unsupported;
}
found = 0;
itemId = 0;
// Debugger will pass in non-normalized paths for remote Linux debugging (produced by concatenating a local Windows-style path
// with a portion of the remote Unix-style path) - need to normalize to look it up.
mkDoc = CommonUtils.NormalizePath(mkDoc);
// If it is the project file just return.
if (CommonUtils.IsSamePath(mkDoc, this.GetMkDocument())) {
found = 1;
itemId = VSConstants.VSITEMID_ROOT;
} else {
HierarchyNode child = this.FindNodeByFullPath(EnsureRootedPath(mkDoc));
if (child != null && (!child.IsNonMemberItem || IncludeNonMemberItemInProject(child))) {
found = 1;
itemId = child.ID;
}
}
if (found == 1) {
if (pri != null && pri.Length >= 1) {
pri[0] = VSDOCUMENTPRIORITY.DP_Standard;
}
}
return VSConstants.S_OK;
}
protected virtual bool IncludeNonMemberItemInProject(HierarchyNode node) {
return false;
}
public virtual int OpenItem(uint itemId, ref Guid logicalView, IntPtr punkDocDataExisting, out IVsWindowFrame frame) {
// Init output params
frame = null;
HierarchyNode n = this.NodeFromItemId(itemId);
if (n == null) {
throw new ArgumentException(SR.GetString(SR.ParameterMustBeAValidItemId), "itemId");
}
// Delegate to the document manager object that knows how to open the item
DocumentManager documentManager = n.GetDocumentManager();
if (documentManager != null) {
return documentManager.Open(ref logicalView, punkDocDataExisting, out frame, WindowFrameShowAction.DoNotShow);
}
// This node does not have an associated document manager and we must fail
return VSConstants.E_FAIL;
}
public virtual int OpenItemWithSpecific(uint itemId, uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame frame) {
// Init output params
frame = null;
HierarchyNode n = this.NodeFromItemId(itemId);
if (n == null) {
throw new ArgumentException(SR.GetString(SR.ParameterMustBeAValidItemId), "itemId");
}
// Delegate to the document manager object that knows how to open the item
DocumentManager documentManager = n.GetDocumentManager();
if (documentManager != null) {
return documentManager.OpenWithSpecific(editorFlags, ref editorType, physicalView, ref logicalView, docDataExisting, out frame, WindowFrameShowAction.DoNotShow);
}
// This node does not have an associated document manager and we must fail
return VSConstants.E_FAIL;
}
public virtual int RemoveItem(uint reserved, uint itemId, out int result) {
HierarchyNode n = this.NodeFromItemId(itemId);
if (n == null) {
throw new ArgumentException(SR.GetString(SR.ParameterMustBeAValidItemId), "itemId");
}
n.Remove(true);
result = 1;
return VSConstants.S_OK;
}
public virtual int ReopenItem(uint itemId, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame frame) {
// Init output params
frame = null;
HierarchyNode n = this.NodeFromItemId(itemId);
if (n == null) {
throw new ArgumentException(SR.GetString(SR.ParameterMustBeAValidItemId), "itemId");
}
// Delegate to the document manager object that knows how to open the item
DocumentManager documentManager = n.GetDocumentManager();
if (documentManager != null) {
return documentManager.ReOpenWithSpecific(0, ref editorType, physicalView, ref logicalView, docDataExisting, out frame, WindowFrameShowAction.DoNotShow);
}
// This node does not have an associated document manager and we must fail
return VSConstants.E_FAIL;
}
/// <summary>
/// Implements IVsProject3::TransferItem
/// This function is called when an open miscellaneous file is being transferred
/// to our project. The sequence is for the shell to call AddItemWithSpecific and
/// then use TransferItem to transfer the open document to our project.
/// </summary>
/// <param name="oldMkDoc">Old document name</param>
/// <param name="newMkDoc">New document name</param>
/// <param name="frame">Optional frame if the document is open</param>
/// <returns></returns>
public virtual int TransferItem(string oldMkDoc, string newMkDoc, IVsWindowFrame frame) {
// Fail if hierarchy already closed
if (this.ProjectMgr == null || this.IsClosed) {
return VSConstants.E_FAIL;
}
//Fail if the document names passed are null.
if (oldMkDoc == null || newMkDoc == null)
return VSConstants.E_INVALIDARG;
int hr = VSConstants.S_OK;
VSDOCUMENTPRIORITY[] priority = new VSDOCUMENTPRIORITY[1];
uint itemid = VSConstants.VSITEMID_NIL;
uint cookie = 0;
uint grfFlags = 0;
IVsRunningDocumentTable pRdt = GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (pRdt == null)
return VSConstants.E_ABORT;
string doc;
int found;
IVsHierarchy pHier;
uint id, readLocks, editLocks;
IntPtr docdataForCookiePtr = IntPtr.Zero;
IntPtr docDataPtr = IntPtr.Zero;
IntPtr hierPtr = IntPtr.Zero;
// We get the document from the running doc table so that we can see if it is transient
try {
ErrorHandler.ThrowOnFailure(pRdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldMkDoc, out pHier, out id, out docdataForCookiePtr, out cookie));
} finally {
if (docdataForCookiePtr != IntPtr.Zero)
Marshal.Release(docdataForCookiePtr);
}
//Get the document info
try {
ErrorHandler.ThrowOnFailure(pRdt.GetDocumentInfo(cookie, out grfFlags, out readLocks, out editLocks, out doc, out pHier, out id, out docDataPtr));
} finally {
if (docDataPtr != IntPtr.Zero)
Marshal.Release(docDataPtr);
}
// Now see if the document is in the project. If not, we fail
try {
ErrorHandler.ThrowOnFailure(IsDocumentInProject(newMkDoc, out found, priority, out itemid));
Debug.Assert(itemid != VSConstants.VSITEMID_NIL && itemid != VSConstants.VSITEMID_ROOT);
hierPtr = Marshal.GetComInterfaceForObject(this, typeof(IVsUIHierarchy));
// Now rename the document
ErrorHandler.ThrowOnFailure(pRdt.RenameDocument(oldMkDoc, newMkDoc, hierPtr, itemid));
} finally {
if (hierPtr != IntPtr.Zero)
Marshal.Release(hierPtr);
}
//Change the caption if we are passed a window frame
if (frame != null) {
var newNode = FindNodeByFullPath(newMkDoc);
if (newNode != null) {
string caption = newNode.Caption;
hr = frame.SetProperty((int)(__VSFPROPID.VSFPROPID_OwnerCaption), caption);
}
}
return hr;
}
#endregion
#region IVsDependencyProvider Members
public int EnumDependencies(out IVsEnumDependencies enumDependencies) {
enumDependencies = new EnumDependencies(this.buildDependencyList);
return VSConstants.S_OK;
}
public int OpenDependency(string szDependencyCanonicalName, out IVsDependency dependency) {
dependency = null;
return VSConstants.S_OK;
}
#endregion
#region IVsComponentUser methods
/// <summary>
/// Add Components to the Project.
/// Used by the environment to add components specified by the user in the Component Selector dialog
/// to the specified project
/// </summary>
/// <param name="dwAddCompOperation">The component operation to be performed.</param>
/// <param name="cComponents">Number of components to be added</param>
/// <param name="rgpcsdComponents">array of component selector data</param>
/// <param name="hwndDialog">Handle to the component picker dialog</param>
/// <param name="pResult">Result to be returned to the caller</param>
public virtual int AddComponent(VSADDCOMPOPERATION dwAddCompOperation, uint cComponents, System.IntPtr[] rgpcsdComponents, System.IntPtr hwndDialog, VSADDCOMPRESULT[] pResult) {
Site.GetUIThread().MustBeCalledFromUIThread();
if (rgpcsdComponents == null || pResult == null) {
return VSConstants.E_FAIL;
}
//initalize the out parameter
pResult[0] = VSADDCOMPRESULT.ADDCOMPRESULT_Success;
IReferenceContainer references = GetReferenceContainer();
if (null == references) {
// This project does not support references or the reference container was not created.
// In both cases this operation is not supported.
return VSConstants.E_NOTIMPL;
}
for (int cCount = 0; cCount < cComponents; cCount++) {
IntPtr ptr = rgpcsdComponents[cCount];
VSCOMPONENTSELECTORDATA selectorData = (VSCOMPONENTSELECTORDATA)Marshal.PtrToStructure(ptr, typeof(VSCOMPONENTSELECTORDATA));
if (null == references.AddReferenceFromSelectorData(selectorData)) {
//Skip further proccessing since a reference has to be added
pResult[0] = VSADDCOMPRESULT.ADDCOMPRESULT_Failure;
return VSConstants.S_OK;
}
}
return VSConstants.S_OK;
}
#endregion
#region IVsSccProject2 Members
/// <summary>
/// This method is called to determine which files should be placed under source control for a given VSITEMID within this hierarchy.
/// </summary>
/// <param name="itemid">Identifier for the VSITEMID being queried.</param>
/// <param name="stringsOut">Pointer to an array of CALPOLESTR strings containing the file names for this item.</param>
/// <param name="flagsOut">Pointer to a CADWORD array of flags stored in DWORDs indicating that some of the files have special behaviors.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int GetSccFiles(uint itemid, CALPOLESTR[] stringsOut, CADWORD[] flagsOut) {
if (itemid == VSConstants.VSITEMID_SELECTION) {
throw new ArgumentException(SR.GetString(SR.InvalidParameter), "itemid");
} else if (itemid == VSConstants.VSITEMID_ROOT) {
// Root node. Return our project file path.
if (stringsOut != null && stringsOut.Length > 0) {
stringsOut[0] = Utilities.CreateCALPOLESTR(new[] { filename });
}
if (flagsOut != null && flagsOut.Length > 0) {
flagsOut[0] = Utilities.CreateCADWORD(new[] { tagVsSccFilesFlags.SFF_NoFlags });
}
return VSConstants.S_OK;
}
// otherwise delegate to either a file or a folder to get the SCC files
HierarchyNode n = this.NodeFromItemId(itemid);
if (n == null) {
throw new ArgumentException(SR.GetString(SR.InvalidParameter), "itemid");
}
List<string> files = new List<string>();
List<tagVsSccFilesFlags> flags = new List<tagVsSccFilesFlags>();
n.GetSccFiles(files, flags);
if (stringsOut != null && stringsOut.Length > 0) {
stringsOut[0] = Utilities.CreateCALPOLESTR(files);
}
if (flagsOut != null && flagsOut.Length > 0) {
flagsOut[0] = Utilities.CreateCADWORD(flags);
}
return VSConstants.S_OK;
}
protected internal override void GetSccFiles(IList<string> files, IList<tagVsSccFilesFlags> flags) {
for (HierarchyNode n = this.FirstChild; n != null; n = n.NextSibling) {
n.GetSccFiles(files, flags);
}
}
protected internal override void GetSccSpecialFiles(string sccFile, IList<string> files, IList<tagVsSccFilesFlags> flags) {
for (HierarchyNode n = this.FirstChild; n != null; n = n.NextSibling) {
n.GetSccSpecialFiles(sccFile, files, flags);
}
}
/// <summary>
/// This method is called to discover special (hidden files) associated with a given VSITEMID within this hierarchy.
/// </summary>
/// <param name="itemid">Identifier for the VSITEMID being queried.</param>
/// <param name="sccFile">One of the files associated with the node</param>
/// <param name="stringsOut">Pointer to an array of CALPOLESTR strings containing the file names for this item.</param>
/// <param name="flagsOut">Pointer to a CADWORD array of flags stored in DWORDs indicating that some of the files have special behaviors.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
/// <remarks>This method is called to discover any special or hidden files associated with an item in the project hierarchy. It is called when GetSccFiles returns with the SFF_HasSpecialFiles flag set for any of the files associated with the node.</remarks>
public virtual int GetSccSpecialFiles(uint itemid, string sccFile, CALPOLESTR[] stringsOut, CADWORD[] flagsOut) {
if (itemid == VSConstants.VSITEMID_SELECTION) {
throw new ArgumentException(SR.GetString(SR.InvalidParameter), "itemid");
}
HierarchyNode n = this.NodeFromItemId(itemid);
if (n == null) {
throw new ArgumentException(SR.GetString(SR.InvalidParameter), "itemid");
}
List<string> files = new List<string>();
List<tagVsSccFilesFlags> flags = new List<tagVsSccFilesFlags>();
n.GetSccSpecialFiles(sccFile, files, flags);
if (stringsOut != null && stringsOut.Length > 0) {
stringsOut[0] = Utilities.CreateCALPOLESTR(files);
}
if (flagsOut != null && flagsOut.Length > 0) {
flagsOut[0] = Utilities.CreateCADWORD(flags);
}
// we have no special files.
return VSConstants.S_OK;
}
/// <summary>
/// This method is called by the source control portion of the environment to inform the project of changes to the source control glyph on various nodes.
/// </summary>
/// <param name="affectedNodes">Count of changed nodes.</param>
/// <param name="itemidAffectedNodes">An array of VSITEMID identifiers of the changed nodes.</param>
/// <param name="newGlyphs">An array of VsStateIcon glyphs representing the new state of the corresponding item in rgitemidAffectedNodes.</param>
/// <param name="newSccStatus">An array of status flags from SccStatus corresponding to rgitemidAffectedNodes. </param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int SccGlyphChanged(int affectedNodes, uint[] itemidAffectedNodes, VsStateIcon[] newGlyphs, uint[] newSccStatus) {
// if all the paramaters are null adn the count is 0, it means scc wants us to updated everything
if (affectedNodes == 0 && itemidAffectedNodes == null && newGlyphs == null && newSccStatus == null) {
ReDrawNode(this, UIHierarchyElement.SccState);
this.UpdateSccStateIcons();
} else if (affectedNodes > 0 && itemidAffectedNodes != null && newGlyphs != null && newSccStatus != null) {
for (int i = 0; i < affectedNodes; i++) {
HierarchyNode n = this.NodeFromItemId(itemidAffectedNodes[i]);
if (n == null) {
throw new ArgumentException(SR.GetString(SR.InvalidParameter), "itemidAffectedNodes");
}
ReDrawNode(n, UIHierarchyElement.SccState);
}
}
return VSConstants.S_OK;
}
/// <summary>
/// This method is called by the source control portion of the environment when a project is initially added to source control, or to change some of the project's settings.
/// </summary>
/// <param name="sccProjectName">String, opaque to the project, that identifies the project location on the server. Persist this string in the project file. </param>
/// <param name="sccLocalPath">String, opaque to the project, that identifies the path to the server. Persist this string in the project file.</param>
/// <param name="sccAuxPath">String, opaque to the project, that identifies the local path to the project. Persist this string in the project file.</param>
/// <param name="sccProvider">String, opaque to the project, that identifies the source control package. Persist this string in the project file.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int SetSccLocation(string sccProjectName, string sccAuxPath, string sccLocalPath, string sccProvider) {
Utilities.ArgumentNotNull("sccProjectName", sccProjectName);
Utilities.ArgumentNotNull("sccAuxPath", sccAuxPath);
Utilities.ArgumentNotNull("sccLocalPath", sccLocalPath);
Utilities.ArgumentNotNull("sccProvider", sccProvider);
// Save our settings (returns true if something changed)
if (!SetSccSettings(sccProjectName, sccLocalPath, sccAuxPath, sccProvider)) {
return VSConstants.S_OK;
}
bool unbinding = (sccProjectName.Length == 0 && sccProvider.Length == 0);
if (unbinding || QueryEditProjectFile(false)) {
buildProject.SetProperty(ProjectFileConstants.SccProjectName, sccProjectName);
buildProject.SetProperty(ProjectFileConstants.SccProvider, sccProvider);
buildProject.SetProperty(ProjectFileConstants.SccAuxPath, sccAuxPath);
buildProject.SetProperty(ProjectFileConstants.SccLocalPath, sccLocalPath);
}
isRegisteredWithScc = true;
return VSConstants.S_OK;
}
#endregion
#region IVsProjectSpecialFiles Members
/// <summary>
/// Allows you to query the project for special files and optionally create them.
/// </summary>
/// <param name="fileId">__PSFFILEID of the file</param>
/// <param name="flags">__PSFFLAGS flags for the file</param>
/// <param name="itemid">The itemid of the node in the hierarchy</param>
/// <param name="fileName">The file name of the special file.</param>
/// <returns></returns>
public virtual int GetFile(int fileId, uint flags, out uint itemid, out string fileName) {
itemid = VSConstants.VSITEMID_NIL;
fileName = String.Empty;
// We need to return S_OK, otherwise the property page tabs will not be shown.
return VSConstants.E_NOTIMPL;
}
#endregion
#region IAggregatedHierarchy Members
/// <summary>
/// Get the inner object of an aggregated hierarchy
/// </summary>
/// <returns>A HierarchyNode</returns>
public virtual HierarchyNode GetInner() {
return this;
}
#endregion
#region IReferenceDataProvider Members
/// <summary>
/// Returns the reference container node.
/// </summary>
/// <returns></returns>
public IReferenceContainer GetReferenceContainer() {
return FindImmediateChild(node => node is IReferenceContainer) as IReferenceContainer;
}
#endregion
#region IBuildDependencyUpdate Members
public virtual IVsBuildDependency[] BuildDependencies {
get {
return this.buildDependencyList.ToArray();
}
}
public virtual void AddBuildDependency(IVsBuildDependency dependency) {
if (this.isClosed || dependency == null) {
return;
}
if (!this.buildDependencyList.Contains(dependency)) {
this.buildDependencyList.Add(dependency);
}
}
public virtual void RemoveBuildDependency(IVsBuildDependency dependency) {
if (this.isClosed || dependency == null) {
return;
}
if (this.buildDependencyList.Contains(dependency)) {
this.buildDependencyList.Remove(dependency);
}
}
#endregion
#region IProjectEventsListener Members
public bool IsProjectEventsListener {
get { return this.isProjectEventsListener; }
set { this.isProjectEventsListener = value; }
}
#endregion
#region IVsAggregatableProject Members
/// <summary>
/// Retrieve the list of project GUIDs that are aggregated together to make this project.
/// </summary>
/// <param name="projectTypeGuids">Semi colon separated list of Guids. Typically, the last GUID would be the GUID of the base project factory</param>
/// <returns>HResult</returns>
public int GetAggregateProjectTypeGuids(out string projectTypeGuids) {
projectTypeGuids = this.GetProjectProperty(ProjectFileConstants.ProjectTypeGuids, false);
// In case someone manually removed this from our project file, default to our project without flavors
if (String.IsNullOrEmpty(projectTypeGuids))
projectTypeGuids = this.ProjectGuid.ToString("B");
return VSConstants.S_OK;
}
/// <summary>
/// This is where the initialization occurs.
/// </summary>
public virtual int InitializeForOuter(string filename, string location, string name, uint flags, ref Guid iid, out IntPtr projectPointer, out int canceled) {
canceled = 0;
projectPointer = IntPtr.Zero;
// Initialize the project
this.Load(filename, location, name, flags, ref iid, out canceled);
if (canceled != 1) {
// Set ourself as the project
IntPtr project = Marshal.GetIUnknownForObject(this);
try {
return Marshal.QueryInterface(project, ref iid, out projectPointer);
} finally {
Marshal.Release(project);
}
}
return VSConstants.OLE_E_PROMPTSAVECANCELLED;
}
/// <summary>
/// This is called after the project is done initializing the different layer of the aggregations
/// </summary>
/// <returns>HResult</returns>
public virtual int OnAggregationComplete() {
return VSConstants.S_OK;
}
/// <summary>
/// Set the list of GUIDs that are aggregated together to create this project.
/// </summary>
/// <param name="projectTypeGuids">Semi-colon separated list of GUIDs, the last one is usually the project factory of the base project factory</param>
/// <returns>HResult</returns>
public int SetAggregateProjectTypeGuids(string projectTypeGuids) {
this.SetProjectProperty(ProjectFileConstants.ProjectTypeGuids, projectTypeGuids);
return VSConstants.S_OK;
}
/// <summary>
/// We are always the inner most part of the aggregation
/// and as such we don't support setting an inner project
/// </summary>
public int SetInnerProject(object innerProject) {
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsProjectFlavorCfgProvider Members
int IVsProjectFlavorCfgProvider.CreateProjectFlavorCfg(IVsCfg pBaseProjectCfg, out IVsProjectFlavorCfg ppFlavorCfg) {
// Our config object is also our IVsProjectFlavorCfg object
ppFlavorCfg = pBaseProjectCfg as IVsProjectFlavorCfg;
return VSConstants.S_OK;
}
#endregion
#region IVsBuildPropertyStorage Members
/// <summary>
/// Get the property of an item
/// </summary>
/// <param name="item">ItemID</param>
/// <param name="attributeName">Name of the property</param>
/// <param name="attributeValue">Value of the property (out parameter)</param>
/// <returns>HRESULT</returns>
int IVsBuildPropertyStorage.GetItemAttribute(uint item, string attributeName, out string attributeValue) {
attributeValue = null;
HierarchyNode node = NodeFromItemId(item);
if (node == null)
throw new ArgumentException("Invalid item id", "item");
if (node.ItemNode != null) {
attributeValue = node.ItemNode.GetMetadata(attributeName);
} else if (node == node.ProjectMgr) {
attributeName = node.ProjectMgr.GetProjectProperty(attributeName);
}
return VSConstants.S_OK;
}
/// <summary>
/// Get the value of the property in the project file
/// </summary>
/// <param name="propertyName">Name of the property to remove</param>
/// <param name="configName">Configuration for which to remove the property</param>
/// <param name="storage">Project or user file (_PersistStorageType)</param>
/// <param name="propertyValue">Value of the property (out parameter)</param>
/// <returns>HRESULT</returns>
public virtual int GetPropertyValue(string propertyName, string configName, uint storage, out string propertyValue) {
// TODO: when adding support for User files, we need to update this method
propertyValue = null;
if (string.IsNullOrEmpty(configName)) {
propertyValue = this.GetProjectProperty(propertyName, false);
} else {
IVsCfg configurationInterface;
int platformStart;
if ((platformStart = configName.IndexOf('|')) != -1) {
// matches C# project system, GetPropertyValue handles display name, not just config name
configName = configName.Substring(0, platformStart);
}
ErrorHandler.ThrowOnFailure(this.ConfigProvider.GetCfgOfName(configName, string.Empty, out configurationInterface));
ProjectConfig config = (ProjectConfig)configurationInterface;
propertyValue = config.GetConfigurationProperty(propertyName, true);
}
return VSConstants.S_OK;
}
/// <summary>
/// Delete a property
/// In our case this simply mean defining it as null
/// </summary>
/// <param name="propertyName">Name of the property to remove</param>
/// <param name="configName">Configuration for which to remove the property</param>
/// <param name="storage">Project or user file (_PersistStorageType)</param>
/// <returns>HRESULT</returns>
int IVsBuildPropertyStorage.RemoveProperty(string propertyName, string configName, uint storage) {
return ((IVsBuildPropertyStorage)this).SetPropertyValue(propertyName, configName, storage, null);
}
/// <summary>
/// Set a property on an item
/// </summary>
/// <param name="item">ItemID</param>
/// <param name="attributeName">Name of the property</param>
/// <param name="attributeValue">New value for the property</param>
/// <returns>HRESULT</returns>
int IVsBuildPropertyStorage.SetItemAttribute(uint item, string attributeName, string attributeValue) {
HierarchyNode node = NodeFromItemId(item);
if (node == null)
throw new ArgumentException("Invalid item id", "item");
node.ItemNode.SetMetadata(attributeName, attributeValue);
return VSConstants.S_OK;
}
/// <summary>
/// Set a project property
/// </summary>
/// <param name="propertyName">Name of the property to set</param>
/// <param name="configName">Configuration for which to set the property</param>
/// <param name="storage">Project file or user file (_PersistStorageType)</param>
/// <param name="propertyValue">New value for that property</param>
/// <returns>HRESULT</returns>
int IVsBuildPropertyStorage.SetPropertyValue(string propertyName, string configName, uint storage, string propertyValue) {
// TODO: when adding support for User files, we need to update this method
if (string.IsNullOrEmpty(configName)) {
this.SetProjectProperty(propertyName, propertyValue);
} else {
IVsCfg configurationInterface;
ErrorHandler.ThrowOnFailure(this.ConfigProvider.GetCfgOfName(configName, string.Empty, out configurationInterface));
ProjectConfig config = (ProjectConfig)configurationInterface;
config.SetConfigurationProperty(propertyName, propertyValue);
}
return VSConstants.S_OK;
}
#endregion
#region private helper methods
/// <summary>
/// Initialize projectNode
/// </summary>
private void Initialize() {
this.ID = VSConstants.VSITEMID_ROOT;
this.tracker = new TrackDocumentsHelper(this);
}
/// <summary>
/// Add an item to the hierarchy based on the item path
/// </summary>
/// <param name="item">Item to add</param>
/// <returns>Added node</returns>
private HierarchyNode AddIndependentFileNode(MSBuild.ProjectItem item, HierarchyNode parent) {
return AddFileNodeToNode(item, parent);
}
/// <summary>
/// Add a dependent file node to the hierarchy
/// </summary>
/// <param name="item">msbuild item to add</param>
/// <param name="parentNode">Parent Node</param>
/// <returns>Added node</returns>
private HierarchyNode AddDependentFileNodeToNode(MSBuild.ProjectItem item, HierarchyNode parentNode) {
FileNode node = this.CreateDependentFileNode(new MsBuildProjectElement(this, item));
parentNode.AddChild(node);
// Make sure to set the HasNameRelation flag on the dependent node if it is related to the parent by name
if (!node.HasParentNodeNameRelation && string.Compare(node.GetRelationalName(), parentNode.GetRelationalName(), StringComparison.OrdinalIgnoreCase) == 0) {
node.HasParentNodeNameRelation = true;
}
return node;
}
/// <summary>
/// Add a file node to the hierarchy
/// </summary>
/// <param name="item">msbuild item to add</param>
/// <param name="parentNode">Parent Node</param>
/// <returns>Added node</returns>
private HierarchyNode AddFileNodeToNode(MSBuild.ProjectItem item, HierarchyNode parentNode) {
FileNode node = this.CreateFileNode(new MsBuildProjectElement(this, item));
parentNode.AddChild(node);
return node;
}
/// <summary>
/// Get the parent node of an msbuild item
/// </summary>
/// <param name="item">msbuild item</param>
/// <returns>parent node</returns>
internal HierarchyNode GetItemParentNode(MSBuild.ProjectItem item) {
Site.GetUIThread().MustBeCalledFromUIThread();
var link = item.GetMetadataValue(ProjectFileConstants.Link);
HierarchyNode currentParent = this;
string strPath = item.EvaluatedInclude;
if (!String.IsNullOrWhiteSpace(link)) {
strPath = Path.GetDirectoryName(link);
} else {
HierarchyNode parent;
if (_diskNodes.TryGetValue(Path.GetDirectoryName(Path.Combine(ProjectHome, strPath)) + "\\", out parent)) {
// fast path, filename is normalized, and the folder already exists
return parent;
}
string absPath = CommonUtils.GetAbsoluteFilePath(ProjectHome, strPath);
if (CommonUtils.IsSubpathOf(ProjectHome, absPath)) {
strPath = CommonUtils.GetRelativeDirectoryPath(ProjectHome, Path.GetDirectoryName(absPath));
} else {
// file lives outside of the project, w/o a link it's just at the top level.
return this;
}
}
if (strPath.Length > 0) {
// Use the relative to verify the folders...
currentParent = this.CreateFolderNodes(strPath);
}
return currentParent;
}
private MSBuildExecution.ProjectPropertyInstance GetMsBuildProperty(string propertyName, bool resetCache) {
if (isDisposed) {
throw new ObjectDisposedException(null);
}
if (resetCache || this.currentConfig == null) {
// Get properties from project file and cache it
this.SetCurrentConfiguration();
this.currentConfig = this.buildProject.CreateProjectInstance();
}
if (this.currentConfig == null) {
throw new Exception(SR.GetString(SR.FailedToRetrieveProperties, propertyName));
}
// return property asked for
return this.currentConfig.GetProperty(propertyName);
}
/// <summary>
/// Updates our scc project settings.
/// </summary>
/// <param name="sccProjectName">String, opaque to the project, that identifies the project location on the server. Persist this string in the project file. </param>
/// <param name="sccLocalPath">String, opaque to the project, that identifies the path to the server. Persist this string in the project file.</param>
/// <param name="sccAuxPath">String, opaque to the project, that identifies the local path to the project. Persist this string in the project file.</param>
/// <param name="sccProvider">String, opaque to the project, that identifies the source control package. Persist this string in the project file.</param>
/// <returns>Returns true if something changed.</returns>
private bool SetSccSettings(string sccProjectName, string sccLocalPath, string sccAuxPath, string sccProvider) {
bool changed = false;
Debug.Assert(sccProjectName != null && sccLocalPath != null && sccAuxPath != null && sccProvider != null);
if (String.Compare(sccProjectName, this.sccProjectName, StringComparison.OrdinalIgnoreCase) != 0 ||
String.Compare(sccLocalPath, this.sccLocalPath, StringComparison.OrdinalIgnoreCase) != 0 ||
String.Compare(sccAuxPath, this.sccAuxPath, StringComparison.OrdinalIgnoreCase) != 0 ||
String.Compare(sccProvider, this.sccProvider, StringComparison.OrdinalIgnoreCase) != 0) {
changed = true;
this.sccProjectName = sccProjectName;
this.sccLocalPath = sccLocalPath;
this.sccAuxPath = sccAuxPath;
this.sccProvider = sccProvider;
}
return changed;
}
/// <summary>
/// Sets the scc info from the project file.
/// </summary>
private void InitSccInfo() {
this.sccProjectName = this.GetProjectProperty(ProjectFileConstants.SccProjectName, false);
this.sccLocalPath = this.GetProjectProperty(ProjectFileConstants.SccLocalPath, false);
this.sccProvider = this.GetProjectProperty(ProjectFileConstants.SccProvider, false);
this.sccAuxPath = this.GetProjectProperty(ProjectFileConstants.SccAuxPath, false);
}
internal void OnAfterProjectOpen() {
this.projectOpened = true;
}
private static XmlElement WrapXmlFragment(XmlDocument document, XmlElement root, Guid flavor, string configuration, string platform, string fragment) {
XmlElement node = document.CreateElement(ProjectFileConstants.FlavorProperties);
XmlAttribute attribute = document.CreateAttribute(ProjectFileConstants.Guid);
attribute.Value = flavor.ToString("B");
node.Attributes.Append(attribute);
if (!String.IsNullOrEmpty(configuration)) {
attribute = document.CreateAttribute(ProjectFileConstants.Configuration);
attribute.Value = configuration;
node.Attributes.Append(attribute);
attribute = document.CreateAttribute(ProjectFileConstants.Platform);
attribute.Value = platform;
node.Attributes.Append(attribute);
}
node.InnerXml = fragment;
root.AppendChild(node);
return node;
}
/// <summary>
/// Sets the project guid from the project file. If no guid is found a new one is created and assigne for the instance project guid.
/// </summary>
private void SetProjectGuidFromProjectFile() {
string projectGuid = this.GetProjectProperty(ProjectFileConstants.ProjectGuid, false);
if (String.IsNullOrEmpty(projectGuid)) {
this.projectIdGuid = Guid.NewGuid();
} else {
Guid guid = new Guid(projectGuid);
if (guid != this.projectIdGuid) {
this.projectIdGuid = guid;
}
}
}
/// <summary>
/// Helper for sharing common code between Build() and BuildAsync()
/// </summary>
/// <param name="output"></param>
/// <returns></returns>
private bool BuildPrelude(IVsOutputWindowPane output) {
bool engineLogOnlyCritical = false;
// If there is some output, then we can ask the build engine to log more than
// just the critical events.
if (null != output) {
engineLogOnlyCritical = BuildEngine.OnlyLogCriticalEvents;
BuildEngine.OnlyLogCriticalEvents = false;
}
this.SetOutputLogger(output);
return engineLogOnlyCritical;
}
/// <summary>
/// Recusively parses the tree and closes all nodes.
/// </summary>
/// <param name="node">The subtree to close.</param>
private static void CloseAllNodes(HierarchyNode node) {
for (HierarchyNode n = node.FirstChild; n != null; n = n.NextSibling) {
if (n.FirstChild != null) {
CloseAllNodes(n);
}
n.Close();
}
}
/// <summary>
/// Set the build project with the new project instance value
/// </summary>
/// <param name="project">The new build project instance</param>
private void SetBuildProject(MSBuild.Project project) {
bool isNewBuildProject = (this.buildProject != project);
this.buildProject = project;
if (this.buildProject != null) {
SetupProjectGlobalPropertiesThatAllProjectSystemsMustSet();
}
if (isNewBuildProject) {
NewBuildProject(project);
}
}
/// <summary>
/// Called when a new value for <see cref="BuildProject"/> is available.
/// </summary>
protected virtual void NewBuildProject(MSBuild.Project project) { }
/// <summary>
/// Setup the global properties for project instance.
/// </summary>
private void SetupProjectGlobalPropertiesThatAllProjectSystemsMustSet() {
string solutionDirectory = null;
string solutionFile = null;
string userOptionsFile = null;
IVsSolution solution = this.Site.GetService(typeof(SVsSolution)) as IVsSolution;
if (solution != null) {
// We do not want to throw. If we cannot set the solution related constants we set them to empty string.
solution.GetSolutionInfo(out solutionDirectory, out solutionFile, out userOptionsFile);
}
if (solutionDirectory == null) {
solutionDirectory = String.Empty;
}
if (solutionFile == null) {
solutionFile = String.Empty;
}
string solutionFileName = Path.GetFileName(solutionFile);
string solutionName = Path.GetFileNameWithoutExtension(solutionFile);
string solutionExtension = Path.GetExtension(solutionFile);
this.buildProject.SetGlobalProperty(GlobalProperty.SolutionDir.ToString(), solutionDirectory);
this.buildProject.SetGlobalProperty(GlobalProperty.SolutionPath.ToString(), solutionFile);
this.buildProject.SetGlobalProperty(GlobalProperty.SolutionFileName.ToString(), solutionFileName);
this.buildProject.SetGlobalProperty(GlobalProperty.SolutionName.ToString(), solutionName);
this.buildProject.SetGlobalProperty(GlobalProperty.SolutionExt.ToString(), solutionExtension);
// Other misc properties
this.buildProject.SetGlobalProperty(GlobalProperty.BuildingInsideVisualStudio.ToString(), "true");
this.buildProject.SetGlobalProperty(GlobalProperty.Configuration.ToString(), ProjectConfig.Debug);
this.buildProject.SetGlobalProperty(GlobalProperty.Platform.ToString(), ProjectConfig.AnyCPU);
// DevEnvDir property
object installDirAsObject = null;
IVsShell shell = this.Site.GetService(typeof(SVsShell)) as IVsShell;
if (shell != null) {
// We do not want to throw. If we cannot set the solution related constants we set them to empty string.
shell.GetProperty((int)__VSSPROPID.VSSPROPID_InstallDirectory, out installDirAsObject);
}
// Ensure that we have traimnling backslash as this is done for the langproj macros too.
string installDir = CommonUtils.NormalizeDirectoryPath((string)installDirAsObject) ?? String.Empty;
this.buildProject.SetGlobalProperty(GlobalProperty.DevEnvDir.ToString(), installDir);
}
/// <summary>
/// Attempts to lock in the privilege of running a build in Visual Studio.
/// </summary>
/// <param name="designTime"><c>false</c> if this build was called for by the Solution Build Manager; <c>true</c> otherwise.</param>
/// <param name="requiresUIThread">
/// Need to claim the UI thread for build under the following conditions:
/// 1. The build must use a resource that uses the UI thread, such as
/// - you set HostServices and you have a host object which requires (even indirectly) the UI thread (VB and C# compilers do this for instance.)
/// or,
/// 2. The build requires the in-proc node AND waits on the UI thread for the build to complete, such as:
/// - you use a ProjectInstance to build, or
/// - you have specified a host object, whether or not it requires the UI thread, or
/// - you set HostServices and you have specified a node affinity.
/// - In addition to the above you also call submission.Execute(), or you call submission.ExecuteAsync() and then also submission.WaitHandle.Wait*().
/// </param>
/// <returns>A value indicating whether a build may proceed.</returns>
/// <remarks>
/// This method must be called on the UI thread.
/// </remarks>
private bool TryBeginBuild(bool designTime, bool requiresUIThread = false) {
IVsBuildManagerAccessor accessor = null;
if (this.Site != null) {
accessor = this.Site.GetService(typeof(SVsBuildManagerAccessor)) as IVsBuildManagerAccessor;
}
bool releaseUIThread = false;
try {
// If the SVsBuildManagerAccessor service is absent, we're not running within Visual Studio.
if (accessor != null) {
if (requiresUIThread) {
int result = accessor.ClaimUIThreadForBuild();
if (result < 0) {
// Not allowed to claim the UI thread right now. Try again later.
return false;
}
releaseUIThread = true; // assume we need to release this immediately until we get through the whole gauntlet.
}
if (designTime) {
int result = accessor.BeginDesignTimeBuild();
if (result < 0) {
// Not allowed to begin a design-time build at this time. Try again later.
return false;
}
}
// We obtained all the resources we need. So don't release the UI thread until after the build is finished.
releaseUIThread = false;
} else {
BuildParameters buildParameters = new BuildParameters(this.buildEngine);
BuildManager.DefaultBuildManager.BeginBuild(buildParameters);
}
this.buildInProcess = true;
return true;
} finally {
// If we were denied the privilege of starting a design-time build,
// we need to release the UI thread.
if (releaseUIThread) {
Debug.Assert(accessor != null, "We think we need to release the UI thread for an accessor we don't have!");
accessor.ReleaseUIThreadForBuild();
}
}
}
/// <summary>
/// Lets Visual Studio know that we're done with our design-time build so others can use the build manager.
/// </summary>
/// <param name="submission">The build submission that built, if any.</param>
/// <param name="designTime">This must be the same value as the one passed to <see cref="TryBeginBuild"/>.</param>
/// <param name="requiresUIThread">This must be the same value as the one passed to <see cref="TryBeginBuild"/>.</param>
/// <remarks>
/// This method must be called on the UI thread.
/// </remarks>
private void EndBuild(BuildSubmission submission, bool designTime, bool requiresUIThread = false) {
IVsBuildManagerAccessor accessor = null;
if (this.Site != null) {
accessor = this.Site.GetService(typeof(SVsBuildManagerAccessor)) as IVsBuildManagerAccessor;
}
if (accessor != null) {
// It's very important that we try executing all three end-build steps, even if errors occur partway through.
try {
if (submission != null) {
Marshal.ThrowExceptionForHR(accessor.UnregisterLoggers(submission.SubmissionId));
}
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
Trace.TraceError(ex.ToString());
}
try {
if (designTime) {
Marshal.ThrowExceptionForHR(accessor.EndDesignTimeBuild());
}
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
Trace.TraceError(ex.ToString());
}
try {
if (requiresUIThread) {
Marshal.ThrowExceptionForHR(accessor.ReleaseUIThreadForBuild());
}
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
Trace.TraceError(ex.ToString());
}
} else {
BuildManager.DefaultBuildManager.EndBuild();
}
this.buildInProcess = false;
}
#endregion
#region IProjectEventsCallback Members
public virtual void BeforeClose() {
}
#endregion
#region IVsProjectBuildSystem Members
public virtual int SetHostObject(string targetName, string taskName, object hostObject) {
Debug.Assert(targetName != null && taskName != null && this.buildProject != null && this.buildProject.Targets != null);
if (targetName == null || taskName == null || this.buildProject == null || this.buildProject.Targets == null) {
return VSConstants.E_INVALIDARG;
}
this.buildProject.ProjectCollection.HostServices.RegisterHostObject(this.buildProject.FullPath, targetName, taskName, (Microsoft.Build.Framework.ITaskHost)hostObject);
return VSConstants.S_OK;
}
public int BuildTarget(string targetName, out bool success) {
success = false;
MSBuildResult result = this.Build(targetName);
if (result == MSBuildResult.Successful) {
success = true;
}
return VSConstants.S_OK;
}
public virtual int CancelBatchEdit() {
return VSConstants.E_NOTIMPL;
}
public virtual int EndBatchEdit() {
return VSConstants.E_NOTIMPL;
}
public virtual int StartBatchEdit() {
return VSConstants.E_NOTIMPL;
}
/// <summary>
/// Used to determine the kind of build system, in VS 2005 there's only one defined kind: MSBuild
/// </summary>
/// <param name="kind"></param>
/// <returns></returns>
public virtual int GetBuildSystemKind(out uint kind) {
kind = (uint)_BuildSystemKindFlags2.BSK_MSBUILD_VS10;
return VSConstants.S_OK;
}
#endregion
/// <summary>
/// Finds a node by it's full path on disk.
/// </summary>
internal HierarchyNode FindNodeByFullPath(string name) {
Site.GetUIThread().MustBeCalledFromUIThread();
Debug.Assert(Path.IsPathRooted(name));
HierarchyNode node;
_diskNodes.TryGetValue(name, out node);
return node;
}
/// <summary>
/// Gets the parent folder if path were added to be added to the hierarchy
/// in it's default (non-linked item) location. Returns null if the path
/// of parent folders to the item don't exist yet.
/// </summary>
/// <param name="path">The full path on disk to the item which is being queried about..</param>
internal HierarchyNode GetParentFolderForPath(string path) {
var parentDir = CommonUtils.GetParent(path);
HierarchyNode parent;
if (CommonUtils.IsSamePath(parentDir, ProjectHome)) {
parent = this;
} else {
parent = FindNodeByFullPath(parentDir);
}
return parent;
}
#region IVsUIHierarchy methods
public virtual int ExecCommand(uint itemId, ref Guid guidCmdGroup, uint nCmdId, uint nCmdExecOpt, IntPtr pvain, IntPtr p) {
return this.InternalExecCommand(guidCmdGroup, nCmdId, nCmdExecOpt, pvain, p, CommandOrigin.UiHierarchy);
}
public virtual int QueryStatusCommand(uint itemId, ref Guid guidCmdGroup, uint cCmds, OLECMD[] cmds, IntPtr pCmdText) {
return this.QueryStatusSelection(guidCmdGroup, cCmds, cmds, pCmdText, CommandOrigin.UiHierarchy);
}
int IVsUIHierarchy.Close() {
return ((IVsHierarchy)this).Close();
}
#endregion
#region IVsHierarchy methods
public virtual int AdviseHierarchyEvents(IVsHierarchyEvents sink, out uint cookie) {
cookie = this._hierarchyEventSinks.Add(sink) + 1;
return VSConstants.S_OK;
}
/// <summary>
/// Closes the project node.
/// </summary>
/// <returns>A success or failure value.</returns>
int IVsHierarchy.Close() {
int hr = VSConstants.S_OK;
try {
Close();
} catch (COMException e) {
hr = e.ErrorCode;
}
return hr;
}
/// <summary>
/// Sets the service provider from which to access the services.
/// </summary>
/// <param name="site">An instance to an Microsoft.VisualStudio.OLE.Interop object</param>
/// <returns>A success or failure value.</returns>
public int SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider site) {
return VSConstants.S_OK;
}
public virtual int GetCanonicalName(uint itemId, out string name) {
HierarchyNode n = NodeFromItemId(itemId);
name = (n != null) ? n.GetCanonicalName() : null;
return VSConstants.S_OK;
}
public virtual int GetGuidProperty(uint itemId, int propid, out Guid guid) {
guid = Guid.Empty;
HierarchyNode n = NodeFromItemId(itemId);
if (n != null) {
int hr = n.GetGuidProperty(propid, out guid);
__VSHPROPID vspropId = (__VSHPROPID)propid;
return hr;
}
if (guid == Guid.Empty) {
return VSConstants.DISP_E_MEMBERNOTFOUND;
}
return VSConstants.S_OK;
}
public virtual int GetProperty(uint itemId, int propId, out object propVal) {
propVal = null;
if (itemId != VSConstants.VSITEMID_ROOT && propId == (int)__VSHPROPID.VSHPROPID_IconImgList) {
return VSConstants.DISP_E_MEMBERNOTFOUND;
}
HierarchyNode n = NodeFromItemId(itemId);
if (n != null) {
propVal = n.GetProperty(propId);
}
if (propVal == null) {
return VSConstants.DISP_E_MEMBERNOTFOUND;
}
return VSConstants.S_OK;
}
public virtual int GetNestedHierarchy(uint itemId, ref Guid iidHierarchyNested, out IntPtr ppHierarchyNested, out uint pItemId) {
ppHierarchyNested = IntPtr.Zero;
pItemId = 0;
// If itemid is not a nested hierarchy we must return E_FAIL.
return VSConstants.E_FAIL;
}
public virtual int GetSite(out Microsoft.VisualStudio.OLE.Interop.IServiceProvider site) {
site = Site.GetService(typeof(Microsoft.VisualStudio.OLE.Interop.IServiceProvider)) as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
return VSConstants.S_OK;
}
/// <summary>
/// the canonicalName of an item is it's URL, or better phrased,
/// the persistence data we put into @RelPath, which is a relative URL
/// to the root project
/// returning the itemID from this means scanning the list
/// </summary>
/// <param name="name"></param>
/// <param name="itemId"></param>
public virtual int ParseCanonicalName(string name, out uint itemId) {
// we always start at the current node and go it's children down, so
// if you want to scan the whole tree, better call
// the root
name = EnsureRootedPath(name);
itemId = 0;
var child = FindNodeByFullPath(name);
if (child != null) {
itemId = child.HierarchyId;
return VSConstants.S_OK;
}
return VSConstants.E_FAIL;
}
private string EnsureRootedPath(string name) {
if (!Path.IsPathRooted(name)) {
name = CommonUtils.GetAbsoluteFilePath(
ProjectHome,
name
);
}
return name;
}
public virtual int QueryClose(out int fCanClose) {
fCanClose = 1;
return VSConstants.S_OK;
}
public virtual int SetGuidProperty(uint itemId, int propid, ref Guid guid) {
HierarchyNode n = NodeFromItemId(itemId);
int rc = VSConstants.E_INVALIDARG;
if (n != null) {
rc = n.SetGuidProperty(propid, ref guid);
}
return rc;
}
public virtual int SetProperty(uint itemId, int propid, object value) {
HierarchyNode n = NodeFromItemId(itemId);
if (n != null) {
return n.SetProperty(propid, value);
} else {
return VSConstants.DISP_E_MEMBERNOTFOUND;
}
}
public virtual int UnadviseHierarchyEvents(uint cookie) {
this._hierarchyEventSinks.RemoveAt(cookie - 1);
return VSConstants.S_OK;
}
public int Unused0() {
return VSConstants.E_NOTIMPL;
}
public int Unused1() {
return VSConstants.E_NOTIMPL;
}
public int Unused2() {
return VSConstants.E_NOTIMPL;
}
public int Unused3() {
return VSConstants.E_NOTIMPL;
}
public int Unused4() {
return VSConstants.E_NOTIMPL;
}
#endregion
#region Hierarchy change notification
internal void OnItemAdded(HierarchyNode parent, HierarchyNode child, HierarchyNode previousVisible = null) {
Utilities.ArgumentNotNull("parent", parent);
Utilities.ArgumentNotNull("child", child);
Site.GetUIThread().MustBeCalledFromUIThread();
IDiskBasedNode diskNode = child as IDiskBasedNode;
if (diskNode != null) {
_diskNodes[diskNode.Url] = child;
}
if ((EventTriggeringFlag & ProjectNode.EventTriggering.DoNotTriggerHierarchyEvents) != 0) {
return;
}
ExtensibilityEventsDispatcher.FireItemAdded(child);
HierarchyNode prev = previousVisible ?? child.PreviousVisibleSibling;
uint prevId = (prev != null) ? prev.HierarchyId : VSConstants.VSITEMID_NIL;
foreach (IVsHierarchyEvents sink in _hierarchyEventSinks) {
int result = sink.OnItemAdded(parent.HierarchyId, prevId, child.HierarchyId);
if (ErrorHandler.Failed(result) && result != VSConstants.E_NOTIMPL) {
ErrorHandler.ThrowOnFailure(result);
}
}
}
internal void OnItemDeleted(HierarchyNode deletedItem) {
Site.GetUIThread().MustBeCalledFromUIThread();
IDiskBasedNode diskNode = deletedItem as IDiskBasedNode;
if (diskNode != null) {
_diskNodes.Remove(diskNode.Url);
}
RaiseItemDeleted(deletedItem);
}
internal void RaiseItemDeleted(HierarchyNode deletedItem) {
if ((EventTriggeringFlag & ProjectNode.EventTriggering.DoNotTriggerHierarchyEvents) != 0) {
return;
}
ExtensibilityEventsDispatcher.FireItemRemoved(deletedItem);
if (_hierarchyEventSinks.Count > 0) {
// Note that in some cases (deletion of project node for example), an Advise
// may be removed while we are iterating over it. To get around this problem we
// take a snapshot of the advise list and walk that.
List<IVsHierarchyEvents> clonedSink = new List<IVsHierarchyEvents>();
foreach (IVsHierarchyEvents anEvent in _hierarchyEventSinks) {
clonedSink.Add(anEvent);
}
foreach (IVsHierarchyEvents clonedEvent in clonedSink) {
int result = clonedEvent.OnItemDeleted(deletedItem.HierarchyId);
if (ErrorHandler.Failed(result) && result != VSConstants.E_NOTIMPL) {
ErrorHandler.ThrowOnFailure(result);
}
}
}
}
internal void OnItemsAppended(HierarchyNode parent) {
Utilities.ArgumentNotNull("parent", parent);
if ((EventTriggeringFlag & ProjectNode.EventTriggering.DoNotTriggerHierarchyEvents) != 0) {
return;
}
foreach (IVsHierarchyEvents sink in _hierarchyEventSinks) {
int result = sink.OnItemsAppended(parent.HierarchyId);
if (ErrorHandler.Failed(result) && result != VSConstants.E_NOTIMPL) {
ErrorHandler.ThrowOnFailure(result);
}
}
}
internal void OnPropertyChanged(HierarchyNode node, int propid, uint flags) {
Utilities.ArgumentNotNull("node", node);
if ((EventTriggeringFlag & ProjectNode.EventTriggering.DoNotTriggerHierarchyEvents) != 0) {
return;
}
foreach (IVsHierarchyEvents sink in _hierarchyEventSinks) {
int result = sink.OnPropertyChanged(node.HierarchyId, propid, flags);
if (ErrorHandler.Failed(result) && result != VSConstants.E_NOTIMPL) {
ErrorHandler.ThrowOnFailure(result);
}
}
}
internal void OnInvalidateItems(HierarchyNode parent) {
Utilities.ArgumentNotNull("parent", parent);
if ((EventTriggeringFlag & ProjectNode.EventTriggering.DoNotTriggerHierarchyEvents) != 0) {
return;
}
bool wasExpanded = ParentHierarchy != null && parent.GetIsExpanded();
foreach (IVsHierarchyEvents sink in _hierarchyEventSinks) {
int result = sink.OnInvalidateItems(parent.HierarchyId);
if (ErrorHandler.Failed(result) && result != VSConstants.E_NOTIMPL) {
ErrorHandler.ThrowOnFailure(result);
}
}
if (wasExpanded) {
parent.ExpandItem(EXPANDFLAGS.EXPF_ExpandFolder);
}
}
/// <summary>
/// Causes the hierarchy to be redrawn.
/// </summary>
/// <param name="element">Used by the hierarchy to decide which element to redraw</param>
internal void ReDrawNode(HierarchyNode node, UIHierarchyElement element) {
foreach (IVsHierarchyEvents sink in _hierarchyEventSinks) {
int result;
if ((element & UIHierarchyElement.Icon) != 0) {
result = sink.OnPropertyChanged(node.ID, (int)__VSHPROPID.VSHPROPID_IconIndex, 0);
Debug.Assert(ErrorHandler.Succeeded(result), "Redraw failed for node " + this.GetMkDocument());
}
if ((element & UIHierarchyElement.Caption) != 0) {
result = sink.OnPropertyChanged(node.ID, (int)__VSHPROPID.VSHPROPID_Caption, 0);
Debug.Assert(ErrorHandler.Succeeded(result), "Redraw failed for node " + this.GetMkDocument());
}
if ((element & UIHierarchyElement.SccState) != 0) {
result = sink.OnPropertyChanged(node.ID, (int)__VSHPROPID.VSHPROPID_StateIconIndex, 0);
Debug.Assert(ErrorHandler.Succeeded(result), "Redraw failed for node " + this.GetMkDocument());
}
}
}
#endregion
#region IVsHierarchyDeleteHandler methods
public virtual int DeleteItem(uint delItemOp, uint itemId) {
if (itemId == VSConstants.VSITEMID_SELECTION) {
return VSConstants.E_INVALIDARG;
}
HierarchyNode node = NodeFromItemId(itemId);
if (node != null) {
node.Remove((delItemOp & (uint)__VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage) != 0);
return VSConstants.S_OK;
}
return VSConstants.E_FAIL;
}
public virtual int QueryDeleteItem(uint delItemOp, uint itemId, out int candelete) {
candelete = 0;
if (itemId == VSConstants.VSITEMID_SELECTION) {
return VSConstants.E_INVALIDARG;
}
// We ask the project what state it is. If he is a state that should not allow delete then we return.
if (IsCurrentStateASuppressCommandsMode()) {
return VSConstants.S_OK;
}
HierarchyNode node = NodeFromItemId(itemId);
if (node == null) {
return VSConstants.E_FAIL;
}
// Ask the nodes if they can remove the item.
bool canDeleteItem = node.CanDeleteItem((__VSDELETEITEMOPERATION)delItemOp);
if (canDeleteItem) {
candelete = 1;
}
return VSConstants.S_OK;
}
#endregion
#region IVsHierarchyDeleteHandler2 methods
public int ShowMultiSelDeleteOrRemoveMessage(uint dwDelItemOp, uint cDelItems, uint[] rgDelItems, out int pfCancelOperation) {
pfCancelOperation = 0;
return VSConstants.S_OK;
}
public int ShowSpecificDeleteRemoveMessage(uint dwDelItemOps, uint cDelItems, uint[] rgDelItems, out int pfShowStandardMessage, out uint pdwDelItemOp) {
pfShowStandardMessage = 1;
pdwDelItemOp = dwDelItemOps;
var items = rgDelItems.Select(id => NodeFromItemId(id)).Where(n => n != null).ToArray();
if (items.Length == 0) {
return VSConstants.S_OK;
} else {
bool cancel, showStandardDialog;
items[0].ShowDeleteMessage(items, (__VSDELETEITEMOPERATION)dwDelItemOps, out cancel, out showStandardDialog);
if (showStandardDialog || cancel) {
pdwDelItemOp = 0;
}
if (!showStandardDialog) {
pfShowStandardMessage = 0;
}
}
return VSConstants.S_OK;
}
#endregion
#region IVsPersistHierarchyItem2 methods
/// <summary>
/// Saves the hierarchy item to disk.
/// </summary>
/// <param name="saveFlag">Flags whose values are taken from the VSSAVEFLAGS enumeration.</param>
/// <param name="silentSaveAsName">New filename when doing silent save as</param>
/// <param name="itemid">Item identifier of the hierarchy item saved from VSITEMID.</param>
/// <param name="docData">Item identifier of the hierarchy item saved from VSITEMID.</param>
/// <param name="cancelled">[out] true if the save action was canceled.</param>
/// <returns>[out] true if the save action was canceled.</returns>
public virtual int SaveItem(VSSAVEFLAGS saveFlag, string silentSaveAsName, uint itemid, IntPtr docData, out int cancelled) {
cancelled = 0;
// Validate itemid
if (itemid == VSConstants.VSITEMID_ROOT || itemid == VSConstants.VSITEMID_SELECTION) {
return VSConstants.E_INVALIDARG;
}
HierarchyNode node = this.NodeFromItemId(itemid);
if (node == null) {
return VSConstants.E_FAIL;
}
string existingFileMoniker = node.GetMkDocument();
// We can only perform save if the document is open
if (docData == IntPtr.Zero) {
throw new InvalidOperationException(SR.GetString(SR.CanNotSaveFileNotOpeneInEditor, node.Url));
}
string docNew = String.Empty;
int returnCode = VSConstants.S_OK;
IPersistFileFormat ff = null;
IVsPersistDocData dd = null;
IVsUIShell shell = Site.GetService(typeof(SVsUIShell)) as IVsUIShell;
Utilities.CheckNotNull(shell);
try {
//Save docdata object.
//For the saveas action a dialog is show in order to enter new location of file.
//In case of a save action and the file is readonly a dialog is also shown
//with a couple of options, SaveAs, Overwrite or Cancel.
ff = Marshal.GetObjectForIUnknown(docData) as IPersistFileFormat;
Utilities.CheckNotNull(ff);
if (VSSAVEFLAGS.VSSAVE_SilentSave == saveFlag) {
ErrorHandler.ThrowOnFailure(shell.SaveDocDataToFile(saveFlag, ff, silentSaveAsName, out docNew, out cancelled));
} else {
dd = Marshal.GetObjectForIUnknown(docData) as IVsPersistDocData;
Utilities.CheckNotNull(dd);
ErrorHandler.ThrowOnFailure(dd.SaveDocData(saveFlag, out docNew, out cancelled));
}
// We can be unloaded after the SaveDocData() call if the save caused a designer to add a file and this caused
// the project file to be reloaded (QEQS caused a newer version of the project file to be downloaded). So we check
// here.
if (IsClosed) {
cancelled = 1;
return (int)OleConstants.OLECMDERR_E_CANCELED;
} else {
// if a SaveAs occurred we need to update to the fact our item's name has changed.
// this includes the following:
// 1. call RenameDocument on the RunningDocumentTable
// 2. update the full path name for the item in our hierarchy
// 3. a directory-based project may need to transfer the open editor to the
// MiscFiles project if the new file is saved outside of the project directory.
// This is accomplished by calling IVsExternalFilesManager::TransferDocument
// we have three options for a saveas action to be performed
// 1. the flag was set (the save as command was triggered)
// 2. a silent save specifying a new document name
// 3. a save command was triggered but was not possible because the file has a read only attrib. Therefore
// the user has chosen to do a save as in the dialog that showed up
bool emptyOrSamePath = String.IsNullOrEmpty(docNew) || CommonUtils.IsSamePath(existingFileMoniker, docNew);
bool saveAs = ((saveFlag == VSSAVEFLAGS.VSSAVE_SaveAs)) ||
((saveFlag == VSSAVEFLAGS.VSSAVE_SilentSave) && !emptyOrSamePath) ||
((saveFlag == VSSAVEFLAGS.VSSAVE_Save) && !emptyOrSamePath);
if (saveAs) {
returnCode = node.AfterSaveItemAs(docData, docNew);
// If it has been cancelled recover the old name.
if ((returnCode == (int)OleConstants.OLECMDERR_E_CANCELED || returnCode == VSConstants.E_ABORT)) {
// Cleanup.
this.DeleteFromStorage(docNew);
if (ff != null) {
returnCode = shell.SaveDocDataToFile(VSSAVEFLAGS.VSSAVE_SilentSave, ff, existingFileMoniker, out docNew, out cancelled);
}
} else if (returnCode != VSConstants.S_OK) {
ErrorHandler.ThrowOnFailure(returnCode);
}
}
}
} catch (COMException e) {
Trace.WriteLine("Exception :" + e.Message);
returnCode = e.ErrorCode;
// Try to recover
// changed from MPFProj:
// http://mpfproj10.codeplex.com/WorkItem/View.aspx?WorkItemId=6982
if (ff != null && cancelled == 0) {
ErrorHandler.ThrowOnFailure(shell.SaveDocDataToFile(VSSAVEFLAGS.VSSAVE_SilentSave, ff, existingFileMoniker, out docNew, out cancelled));
}
}
return returnCode;
}
/// <summary>
/// Determines whether the hierarchy item changed.
/// </summary>
/// <param name="itemId">Item identifier of the hierarchy item contained in VSITEMID.</param>
/// <param name="docData">Pointer to the IUnknown interface of the hierarchy item.</param>
/// <param name="isDirty">true if the hierarchy item changed.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int IsItemDirty(uint itemId, IntPtr docData, out int isDirty) {
IVsPersistDocData pd = (IVsPersistDocData)Marshal.GetObjectForIUnknown(docData);
return ErrorHandler.ThrowOnFailure(pd.IsDocDataDirty(out isDirty));
}
/// <summary>
/// Flag indicating that changes to a file can be ignored when item is saved or reloaded.
/// </summary>
/// <param name="itemId">Specifies the item id from VSITEMID.</param>
/// <param name="ignoreFlag">Flag indicating whether or not to ignore changes (1 to ignore, 0 to stop ignoring).</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
public virtual int IgnoreItemFileChanges(uint itemId, int ignoreFlag) {
HierarchyNode n = this.NodeFromItemId(itemId);
if (n != null) {
n.IgnoreItemFileChanges(ignoreFlag == 0 ? false : true);
}
return VSConstants.S_OK;
}
/// <summary>
/// Called to determine whether a project item is reloadable before calling ReloadItem.
/// </summary>
/// <param name="itemId">Item identifier of an item in the hierarchy. Valid values are VSITEMID_NIL, VSITEMID_ROOT and VSITEMID_SELECTION.</param>
/// <param name="isReloadable">A flag indicating that the project item is reloadable (1 for reloadable, 0 for non-reloadable).</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int IsItemReloadable(uint itemId, out int isReloadable) {
isReloadable = 0;
HierarchyNode n = this.NodeFromItemId(itemId);
if (n != null) {
isReloadable = (n.IsItemReloadable()) ? 1 : 0;
}
return VSConstants.S_OK;
}
/// <summary>
/// Called to reload a project item.
/// </summary>
/// <param name="itemId">Specifies itemid from VSITEMID.</param>
/// <param name="reserved">Reserved.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int ReloadItem(uint itemId, uint reserved) {
HierarchyNode n = this.NodeFromItemId(itemId);
if (n != null) {
n.ReloadItem(reserved);
}
return VSConstants.S_OK;
}
#endregion
public void UpdatePathForDeferredSave(string oldPath, string newPath) {
Site.GetUIThread().MustBeCalledFromUIThread();
var existing = _diskNodes[oldPath];
_diskNodes.Remove(oldPath);
_diskNodes.Add(newPath, existing);
}
public IVsHierarchy ParentHierarchy {
get {
return parentHierarchy;
}
}
[Conditional("DEBUG")]
internal void AssertHasParentHierarchy() {
// Calling into solution explorer before a parent hierarchy is assigned can
// cause us to corrupt solution explorer if we're using flavored projects. We
// will call in with our inner project node and later we get wrapped in an
// aggregate COM object which has different object identity. At that point
// solution explorer is confused because it uses object identity to track
// the hierarchies.
Debug.Assert(parentHierarchy != null, "dont call into the hierarchy before the project is loaded, it corrupts the hierarchy");
}
}
}
| 45.213056 | 292 | 0.561499 | [
"Apache-2.0"
] | Weflac/nodejstools | Common/Product/SharedProject/ProjectNode.cs | 269,570 | C# |
namespace TypeReferences.Demo.Editor
{
using UnityEditor;
using UnityEngine;
internal static class InfoBox
{
public static void Draw(string text)
{
// Used to add some margin between the the HelpBox and the property.
const float marginHeight = 2f;
Rect infoBoxArea = EditorGUILayout.GetControlRect(false, GetInfoBoxHeight(text, marginHeight));
infoBoxArea.height -= marginHeight;
EditorGUI.HelpBox(infoBoxArea, text, MessageType.Info);
}
private static float GetInfoBoxHeight(string text, float marginHeight)
{
// This stops icon shrinking if text content doesn't fill out the container enough.
const float minHeight = 40f;
// currentViewWidth is the whole width of Inspector. Text box width is smaller than that.
float textBoxWidth = EditorGUIUtility.currentViewWidth - 65f;
var content = new GUIContent(text);
var style = GUI.skin.GetStyle("helpbox");
float height = style.CalcHeight(content, textBoxWidth);
// We add tiny padding here to make sure the text is not overflowing the HelpBox from the top
// and bottom.
height += marginHeight * 2;
return height > minHeight ? height : minHeight;
}
}
} | 36.236842 | 107 | 0.628177 | [
"MIT"
] | DanAmador/ClassTypeReference-for-Unity | Samples~/Usage Examples/Editor/InfoBox.cs | 1,379 | C# |
using SlipeServer.Scripting.EventDefinitions;
using SlipeServer.Server.Elements;
using System;
namespace SlipeServer.Scripting
{
public interface IScriptEventRuntime
{
void AddEventHandler(string eventName, Element attachedTo, EventDelegate callbackDelegate);
void RemoveEventHandler(string eventName, Element attachedTo, EventDelegate callbackDelegate);
void LoadEvents(IEventDefinitions eventDefinitions);
void LoadDefaultEvents();
void RegisterEvent<T>(string eventName, EventRegistrationDelegate<T> eventDelegate) where T : Element;
}
public delegate void EventDelegate(Element element, params object[] parameters);
public delegate EventHandlerActions<T> EventRegistrationDelegate<T>(Element element, ScriptCallbackDelegate callback) where T : Element;
public struct EventHandlerActions<T> where T : Element
{
public Action<T> Add { get; set; }
public Action<T> Remove { get; set; }
}
}
| 39.36 | 140 | 0.748984 | [
"MIT"
] | ChronosX88/Slipe-Server | SlipeServer.Scripting/IScriptEventRuntime.cs | 986 | C# |
using SecondHand.Data.Models;
using SecondHand.Data.Repositories.Base;
using SecondHand.Data.Repositories.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SecondHand.Data.Repositories
{
public class NotificationsRepository : EfRepository<ChatNotification>, INotificationsRepository
{
public NotificationsRepository(MsSqlDbContext context)
: base(context)
{
}
}
}
| 25.1 | 99 | 0.750996 | [
"MIT"
] | vixataaa/asp-project | src/SecondHand/SecondHand.Data/Repositories/NotificationsRepository.cs | 504 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
namespace PTSharp
{
class STL
{
// Binary STL reader is based on the article by Frank Niemeyer
// http://frankniemeyer.blogspot.gr/2014/05/binary-stl-io-using-nativeinteropstream.html
// Requires NativeInterop from Nuget
// https://www.nuget.org/packages/NativeInterop/
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct STLVector
{
public float X;
public float Y;
public float Z;
public STLVector(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct STLTriangle
{
// 4 * 3 * 4 byte + 2 byte = 50 byte
public STLVector Normal;
public STLVector A;
public STLVector B;
public STLVector C;
public ushort AttributeByteCount;
public STLTriangle(
STLVector normalVec,
STLVector vertex1,
STLVector vertex2,
STLVector vertex3,
ushort attr = 0)
{
Normal = normalVec;
A = vertex1;
B = vertex2;
C = vertex3;
AttributeByteCount = attr;
}
}
STLTriangle[] mesh = new STLTriangle[] {
new STLTriangle(new STLVector(0, 0, 0),
new STLVector(0, 0, 0),
new STLVector(0, 1, 0),
new STLVector(1, 0, 0)),
new STLTriangle(new STLVector(0, 0, 0),
new STLVector(0, 0, 0),
new STLVector(0, 0, 1),
new STLVector(0, 1, 0)),
new STLTriangle(new STLVector(0, 0, 0),
new STLVector(0, 0, 0),
new STLVector(0, 0, 1),
new STLVector(1, 0, 0)),
new STLTriangle(new STLVector(0, 0, 0),
new STLVector(0, 1, 0),
new STLVector(0, 0, 1),
new STLVector(1, 0, 0)),
};
public static Mesh Load(String filePath, Material material)
{
byte[] buffer = new byte[80];
FileInfo fi = new FileInfo(filePath);
BinaryReader reader;
long size;
if (File.Exists(filePath))
{
Console.WriteLine("Loading STL:" + filePath);
size = fi.Length;
bool isReadOnly = fi.IsReadOnly;
using (reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
{
buffer = reader.ReadBytes(80);
reader.ReadBytes(4);
int filelength = (int)reader.BaseStream.Length;
string code = reader.ReadByte().ToString() + reader.ReadByte().ToString();
reader.BaseStream.Close();
//Console.WriteLine("Code = " + code);
if (code.Equals("00") || code.Equals("10181") || code.Equals("8689") || code.Equals("19593"))
{
return LoadSTLB(filePath, material);
} else {
return LoadSTLA(filePath, material);
}
}
}
else
{
Console.WriteLine("Specified file could not be opened...");
return null;
}
}
public static Mesh LoadSTLA(String filename, Material material)
{
string line = null;
int counter = 0;
// Creating storage structures for storing facets, vertex and normals
List<Vector> facetnormal = new List<Vector>();
List<Vector> vertexes = new List<Vector>();
List<Triangle> triangles = new List<Triangle>();
Vector[] varray;
Match match = null;
const string regex = @"\s*(facet normal|vertex)\s+(?<X>[^\s]+)\s+(?<Y>[^\s]+)\s+(?<Z>[^\s]+)";
const NumberStyles numberStyle = (NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign);
StreamReader file = new StreamReader(filename);
// Reading text filled STL file
try
{
// Checking to see if the file header has proper structure and that the file does contain something
if ((line = file.ReadLine()) != null && line.Contains("solid"))
{
counter++;
//While there are lines to be read in the file
while ((line = file.ReadLine()) != null && !line.Contains("endsolid"))
{
counter++;
if (line.Contains("normal"))
{
match = Regex.Match(line, regex, RegexOptions.IgnoreCase);
//Reading facet
//Console.WriteLine("Read facet on line " + counter);
double.TryParse(match.Groups["X"].Value, numberStyle, CultureInfo.InvariantCulture, out double x);
double.TryParse(match.Groups["Y"].Value, numberStyle, CultureInfo.InvariantCulture, out double y);
double.TryParse(match.Groups["Z"].Value, numberStyle, CultureInfo.InvariantCulture, out double z);
Vector f = new Vector(x, y, z);
//Console.WriteLine("Added facet (x,y,z)"+ " "+x+" "+y+" "+z);
facetnormal.Add(f);
}
line = file.ReadLine();
counter++;
// Checking if we are in the outer loop line
if (line.Contains("outer loop"))
{
//Console.WriteLine("Outer loop");
line = file.ReadLine();
counter++;
}
if (line.Contains("vertex"))
{
match = Regex.Match(line, regex, RegexOptions.IgnoreCase);
//Console.WriteLine("Read vertex on line " + counter);
double.TryParse(match.Groups["X"].Value, numberStyle, CultureInfo.InvariantCulture, out double x);
double.TryParse(match.Groups["Y"].Value, numberStyle, CultureInfo.InvariantCulture, out double y);
double.TryParse(match.Groups["Z"].Value, numberStyle, CultureInfo.InvariantCulture, out double z);
Vector v = new Vector(x, y, z);
//Console.WriteLine("Added vertex 1 (x,y,z)" + " " + x + " " + y + " " + z);
vertexes.Add(v);
}
line = file.ReadLine();
counter++;
if (line.Contains("vertex"))
{
match = Regex.Match(line, regex, RegexOptions.IgnoreCase);
//Console.WriteLine("Read vertex on line " + counter);
double.TryParse(match.Groups["X"].Value, numberStyle, CultureInfo.InvariantCulture, out double x);
double.TryParse(match.Groups["Y"].Value, numberStyle, CultureInfo.InvariantCulture, out double y);
double.TryParse(match.Groups["Z"].Value, numberStyle, CultureInfo.InvariantCulture, out double z);
Vector v = new Vector(x, y, z);
//Console.WriteLine("Added vertex 2 (x,y,z)" + " " + x + " " + y + " " + z);
vertexes.Add(v);
line = file.ReadLine();
counter++;
}
if (line.Contains("vertex"))
{
match = Regex.Match(line, regex, RegexOptions.IgnoreCase);
//Console.WriteLine("Read vertex on line " + counter);
double.TryParse(match.Groups["X"].Value, numberStyle, CultureInfo.InvariantCulture, out double x);
double.TryParse(match.Groups["Y"].Value, numberStyle, CultureInfo.InvariantCulture, out double y);
double.TryParse(match.Groups["Z"].Value, numberStyle, CultureInfo.InvariantCulture, out double z);
Vector v = new Vector(x, y, z);
//Console.WriteLine("Added vertex 3 (x,y,z)" + " " + x + " " + y + " " + z);
vertexes.Add(v);
line = file.ReadLine();
counter++;
}
if (line.Contains("endloop"))
{
//Console.WriteLine("End loop");
line = file.ReadLine();
counter++;
}
if (line.Contains("endfacet"))
{
//Console.WriteLine("End facet");
line = file.ReadLine();
counter++;
if (line.Contains("endsolid"))
{
varray = vertexes.ToArray();
for (int i = 0; i < varray.Length; i += 3)
{
Triangle t = new Triangle(varray[i + 0], varray[i + 1], varray[i + 2], material);
t.FixNormals();
triangles.Add(t);
}
break;
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
return null;
}
file.Close();
return Mesh.NewMesh(triangles.ToArray());
}
public static Mesh LoadSTLB(String filename, Material material)
{
string header;
STLTriangle[] mesh;
using (var br = new BinaryReader(File.OpenRead(filename), Encoding.ASCII))
{
header = Encoding.ASCII.GetString(br.ReadBytes(80));
var triCount = br.ReadUInt32();
mesh = null; // br.BaseStream.ReadUnmanagedStructRange<STLTriangle>((int)triCount);
}
List<Triangle> tlist = new List<Triangle>();
foreach (STLTriangle m in mesh)
{
Triangle t = new Triangle(new Vector(m.A.X, m.A.Y, m.A.Z), new Vector(m.B.X, m.B.Y, m.B.Z), new Vector(m.C.X, m.C.Y, m.C.Z), material);
t.FixNormals();
tlist.Add(t);
}
return Mesh.NewMesh(tlist.ToArray());
}
}
}
| 43.198556 | 152 | 0.432392 | [
"MIT"
] | xfischer/PTSharp | STL.cs | 11,966 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using SteamAuth;
using System.IO.Ports;
namespace SteamAuthConsole
{
class Program
{
static void Main(string[] args)
{
SteamGuardAccount account = new SteamGuardAccount();
account.SharedSecret = args[0];
string loginCode = account.GenerateSteamGuardCode();
Console.Write(loginCode);
}
}
}
| 23.304348 | 65 | 0.634328 | [
"MIT"
] | CrafterOfWorlds/SteamAuthConsole | Program.cs | 538 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DragonFruit.Six.Locale.Objects {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Weapons {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Weapons() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DragonFruit.Six.Locale.Objects.Weapons", typeof(Weapons).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Assault Rifle.
/// </summary>
public static string AssaultRifle {
get {
return ResourceManager.GetString("AssaultRifle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Launcher.
/// </summary>
public static string Launcher {
get {
return ResourceManager.GetString("Launcher", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Light Machine Gun.
/// </summary>
public static string LightMachineGun {
get {
return ResourceManager.GetString("LightMachineGun", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Machine Pistol.
/// </summary>
public static string MachinePistol {
get {
return ResourceManager.GetString("MachinePistol", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Pistol.
/// </summary>
public static string Pistol {
get {
return ResourceManager.GetString("Pistol", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shield.
/// </summary>
public static string Shield {
get {
return ResourceManager.GetString("Shield", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Shotgun.
/// </summary>
public static string Shotgun {
get {
return ResourceManager.GetString("Shotgun", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Sniper Rifle.
/// </summary>
public static string Sniper {
get {
return ResourceManager.GetString("Sniper", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Submachine Gun.
/// </summary>
public static string SubmachineGun {
get {
return ResourceManager.GetString("SubmachineGun", resourceCulture);
}
}
}
}
| 36.848276 | 181 | 0.557365 | [
"MIT"
] | dragonfruitnetwork/Dragon6-Locale | DragonFruit.Six.Locale/Objects/Weapons.Designer.cs | 5,345 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 Microsoft.Azure.Batch;
using Microsoft.Azure.Commands.Batch.Properties;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Microsoft.Azure.Commands.Batch.Models
{
public partial class BatchClient
{
/// <summary>
/// Lists the job schedules matching the specified filter options.
/// </summary>
/// <param name="options">The options to use when querying for job schedules.</param>
/// <returns>The workitems matching the specified filter options.</returns>
public IEnumerable<PSCloudJobSchedule> ListJobSchedules(ListJobScheduleOptions options)
{
if (options == null)
{
throw new ArgumentNullException("options");
}
// Get the single job schedule matching the specified id
if (!string.IsNullOrWhiteSpace(options.JobScheduleId))
{
WriteVerbose(string.Format(Resources.GetJobScheduleById, options.JobScheduleId));
JobScheduleOperations jobScheduleOperations = options.Context.BatchOMClient.JobScheduleOperations;
ODATADetailLevel getDetailLevel = new ODATADetailLevel(selectClause: options.Select, expandClause: options.Expand);
CloudJobSchedule jobSchedule = jobScheduleOperations.GetJobSchedule(options.JobScheduleId, detailLevel: getDetailLevel, additionalBehaviors: options.AdditionalBehaviors);
PSCloudJobSchedule psJobSchedule = new PSCloudJobSchedule(jobSchedule);
return new PSCloudJobSchedule[] { psJobSchedule };
}
// List job schedules using the specified filter
else
{
string verboseLogString = null;
ODATADetailLevel listDetailLevel = new ODATADetailLevel(selectClause: options.Select, expandClause: options.Expand);
if (!string.IsNullOrEmpty(options.Filter))
{
verboseLogString = Resources.GetJobScheduleByOData;
listDetailLevel.FilterClause = options.Filter;
}
else
{
verboseLogString = Resources.GetJobScheduleNoFilter;
}
WriteVerbose(verboseLogString);
JobScheduleOperations jobScheduleOperations = options.Context.BatchOMClient.JobScheduleOperations;
IPagedEnumerable<CloudJobSchedule> workItems = jobScheduleOperations.ListJobSchedules(listDetailLevel, options.AdditionalBehaviors);
Func<CloudJobSchedule, PSCloudJobSchedule> mappingFunction = j => { return new PSCloudJobSchedule(j); };
return PSPagedEnumerable<PSCloudJobSchedule, CloudJobSchedule>.CreateWithMaxCount(
workItems, mappingFunction, options.MaxCount, () => WriteVerbose(string.Format(Resources.MaxCount, options.MaxCount)));
}
}
/// <summary>
/// Creates a new job schedule.
/// </summary>
/// <param name="parameters">The parameters to use when creating the job schedule.</param>
public void CreateJobSchedule(NewJobScheduleParameters parameters)
{
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
JobScheduleOperations jobScheduleOperations = parameters.Context.BatchOMClient.JobScheduleOperations;
CloudJobSchedule jobSchedule = jobScheduleOperations.CreateJobSchedule();
jobSchedule.Id = parameters.JobScheduleId;
jobSchedule.DisplayName = parameters.DisplayName;
if (parameters.Schedule != null)
{
jobSchedule.Schedule = parameters.Schedule.omObject;
}
if (parameters.JobSpecification != null)
{
Utils.Utils.JobSpecificationSyncCollections(parameters.JobSpecification);
jobSchedule.JobSpecification = parameters.JobSpecification.omObject;
}
if (parameters.Metadata != null)
{
jobSchedule.Metadata = new List<MetadataItem>();
foreach (DictionaryEntry d in parameters.Metadata)
{
MetadataItem metadata = new MetadataItem(d.Key.ToString(), d.Value.ToString());
jobSchedule.Metadata.Add(metadata);
}
}
WriteVerbose(string.Format(Resources.CreatingJobSchedule, parameters.JobScheduleId));
jobSchedule.Commit(parameters.AdditionalBehaviors);
}
/// <summary>
/// Commits changes to a PSCloudJobSchedule object to the Batch Service.
/// </summary>
/// <param name="context">The account to use.</param>
/// <param name="jobSchedule">The PSCloudJobSchedule object representing the job schedule to update.</param>
/// <param name="additionBehaviors">Additional client behaviors to perform.</param>
public void UpdateJobSchedule(BatchAccountContext context, PSCloudJobSchedule jobSchedule, IEnumerable<BatchClientBehavior> additionBehaviors = null)
{
if (jobSchedule == null)
{
throw new ArgumentNullException("jobSchedule");
}
WriteVerbose(string.Format(Resources.UpdatingJobSchedule, jobSchedule.Id));
Utils.Utils.BoundJobScheduleSyncCollections(jobSchedule);
jobSchedule.omObject.Commit(additionBehaviors);
}
/// <summary>
/// Deletes the specified job schedule.
/// </summary>
/// <param name="context">The account to use.</param>
/// <param name="jobScheduleId">The id of the job schedule to delete.</param>
/// <param name="additionBehaviors">Additional client behaviors to perform.</param>
public void DeleteJobSchedule(BatchAccountContext context, string jobScheduleId, IEnumerable<BatchClientBehavior> additionBehaviors = null)
{
if (string.IsNullOrWhiteSpace(jobScheduleId))
{
throw new ArgumentNullException("jobScheduleId");
}
JobScheduleOperations jobScheduleOperations = context.BatchOMClient.JobScheduleOperations;
jobScheduleOperations.DeleteJobSchedule(jobScheduleId, additionBehaviors);
}
/// <summary>
/// Enables the specified job schedule.
/// </summary>
/// <param name="context">The account to use.</param>
/// <param name="jobScheduleId">The id of the job schedule to enable.</param>
/// <param name="additionBehaviors">Additional client behaviors to perform.</param>
public void EnableJobSchedule(BatchAccountContext context, string jobScheduleId, IEnumerable<BatchClientBehavior> additionBehaviors = null)
{
if (string.IsNullOrWhiteSpace(jobScheduleId))
{
throw new ArgumentNullException("jobScheduleId");
}
WriteVerbose(string.Format(Resources.EnableJobSchedule, jobScheduleId));
JobScheduleOperations jobScheduleOperations = context.BatchOMClient.JobScheduleOperations;
jobScheduleOperations.EnableJobSchedule(jobScheduleId, additionBehaviors);
}
/// <summary>
/// Disables the specified job schedule.
/// </summary>
/// <param name="context">The account to use.</param>
/// <param name="jobScheduleId">The id of the job schedule to disable.</param>
/// <param name="additionBehaviors">Additional client behaviors to perform.</param>
public void DisableJobSchedule(BatchAccountContext context, string jobScheduleId, IEnumerable<BatchClientBehavior> additionBehaviors = null)
{
if (string.IsNullOrWhiteSpace(jobScheduleId))
{
throw new ArgumentNullException("jobScheduleId");
}
WriteVerbose(string.Format(Resources.DisableJobSchedule, jobScheduleId));
JobScheduleOperations jobScheduleOperations = context.BatchOMClient.JobScheduleOperations;
jobScheduleOperations.DisableJobSchedule(jobScheduleId, additionBehaviors);
}
/// <summary>
/// Terminates the specified job schedule.
/// </summary>
/// <param name="context">The account to use.</param>
/// <param name="jobScheduleId">The id of the job schedule to terminate.</param>
/// <param name="additionBehaviors">Additional client behaviors to perform.</param>
public void TerminateJobSchedule(BatchAccountContext context, string jobScheduleId, IEnumerable<BatchClientBehavior> additionBehaviors = null)
{
if (string.IsNullOrWhiteSpace(jobScheduleId))
{
throw new ArgumentNullException("jobScheduleId");
}
WriteVerbose(string.Format(Resources.TerminateJobSchedule, jobScheduleId));
JobScheduleOperations jobScheduleOperations = context.BatchOMClient.JobScheduleOperations;
jobScheduleOperations.TerminateJobSchedule(jobScheduleId, additionBehaviors);
}
}
}
| 49.495146 | 187 | 0.631718 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Batch/Batch/Models/BatchClient.JobSchedules.cs | 9,993 | C# |
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using NGitLab.Extensions;
using NGitLab.Models;
namespace NGitLab.Impl
{
public partial class HttpRequestor
{
/// <summary>
/// A single request to gitlab, that can be retried.
/// </summary>
private sealed class GitLabRequest
{
public Uri Url { get; }
private object Data { get; }
public string JsonData { get; }
public FormDataContent FormData { get; }
private MethodType Method { get; }
public WebHeaderCollection Headers { get; } = new WebHeaderCollection();
private bool HasOutput
=> (Method == MethodType.Delete || Method == MethodType.Post || Method == MethodType.Put)
&& Data != null;
public GitLabRequest(Uri url, MethodType method, object data, string apiToken, string sudo = null)
{
Method = method;
Url = url;
Data = data;
Headers.Add("Accept-Encoding", "gzip");
if (!string.IsNullOrEmpty(sudo))
{
Headers.Add("Sudo", sudo);
}
if (apiToken != null)
{
Headers.Add("Private-Token", apiToken);
}
if (data is FormDataContent formData)
{
FormData = formData;
}
else if (data != null)
{
JsonData = SimpleJson.SerializeObject(data);
}
}
public WebResponse GetResponse(RequestOptions options)
{
Func<WebResponse> getResponseImpl = () => GetResponseImpl(options);
return getResponseImpl.Retry(options.ShouldRetry,
options.RetryInterval,
options.RetryCount,
options.IsIncremental);
}
private WebResponse GetResponseImpl(RequestOptions options)
{
try
{
var request = CreateRequest(options.HttpClientTimeout);
return options.GetResponse(request);
}
catch (WebException wex)
{
if (wex.Response == null)
{
throw;
}
using var errorResponse = (HttpWebResponse)wex.Response;
string jsonString;
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
jsonString = reader.ReadToEnd();
}
var errorMessage = ExtractErrorMessage(jsonString, out var parsedError);
var exceptionMessage =
$"GitLab server returned an error ({errorResponse.StatusCode}): {errorMessage}. " +
$"Original call: {Method} {Url}";
if (JsonData != null)
{
exceptionMessage += $". With data {JsonData}";
}
throw new GitLabException(exceptionMessage)
{
OriginalCall = Url,
ErrorObject = parsedError,
StatusCode = errorResponse.StatusCode,
ErrorMessage = errorMessage,
};
}
}
private HttpWebRequest CreateRequest(TimeSpan httpClientTimeout)
{
var request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = Method.ToString().ToUpperInvariant();
request.Accept = "application/json";
request.Headers = Headers;
request.AutomaticDecompression = DecompressionMethods.GZip;
request.Timeout = (int)httpClientTimeout.TotalMilliseconds;
request.ReadWriteTimeout = (int)httpClientTimeout.TotalMilliseconds;
if (HasOutput)
{
if (FormData != null)
{
AddFileData(request);
}
else if (JsonData != null)
{
AddJsonData(request);
}
}
else if (Method == MethodType.Put)
{
request.ContentLength = 0;
}
return request;
}
private void AddJsonData(WebRequest request)
{
request.ContentType = "application/json";
using var writer = new StreamWriter(request.GetRequestStream());
writer.Write(JsonData);
writer.Flush();
writer.Close();
}
public void AddFileData(WebRequest request)
{
var boundary = $"--------------------------{DateTime.UtcNow.Ticks}";
if (Data is not FormDataContent formData)
return;
request.ContentType = "multipart/form-data; boundary=" + boundary;
using var uploadContent = new MultipartFormDataContent(boundary)
{
{ new StreamContent(formData.Stream), "file", formData.Name },
};
uploadContent.CopyToAsync(request.GetRequestStream()).Wait();
}
/// <summary>
/// Parse the error that GitLab returns. GitLab returns structured errors but has a lot of them
/// Here we try to be generic.
/// </summary>
/// <param name="json"></param>
/// <param name="parsedError"></param>
/// <returns></returns>
private static string ExtractErrorMessage(string json, out JsonObject parsedError)
{
if (string.IsNullOrEmpty(json))
{
parsedError = null;
return "Empty Response";
}
SimpleJson.TryDeserializeObject(json, out var errorObject);
parsedError = errorObject as JsonObject;
object messageObject = null;
if (parsedError?.TryGetValue("message", out messageObject) != true)
{
parsedError?.TryGetValue("error", out messageObject);
}
if (messageObject == null)
{
return $"Error message cannot be parsed ({json})";
}
if (messageObject is string str)
{
return str;
}
return SimpleJson.SerializeObject(messageObject);
}
}
}
}
| 34.53202 | 110 | 0.468474 | [
"MIT"
] | ubisoft/NGitLabBackup | NGitLab/Impl/HttpRequestor.GitLabRequest.cs | 7,012 | C# |
using System;
using System.IO;
using System.Security.Cryptography;
namespace ByteDev.Crypto.Hashing.Algorithms
{
/// <summary>
/// Represents the hashing algorithm HMACSHA256.
/// </summary>
public class HmacSha256Algorithm : IHashAlgorithm
{
private readonly string _key;
/// <summary>
/// Initializes a new instance of the <see cref="T:ByteDev.Crypto.Hashing.Algorithms.HmacSha256Algorithm" /> class.
/// </summary>
/// <param name="key">Algorithm key to use when performing a hash operation.</param>
public HmacSha256Algorithm(string key)
{
_key = key;
}
/// <summary>
/// Hash <paramref name="data" />.
/// </summary>
/// <param name="data">The data to hash.</param>
/// <returns>The hash of <paramref name="data" />.</returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="data" /> is null.</exception>
public byte[] Hash(byte[] data)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (data.Length < 1)
return new byte[0];
using (var sha = new HMACSHA256(System.Text.Encoding.UTF8.GetBytes(_key)))
{
return sha.ComputeHash(data);
}
}
/// <summary>
/// Hash <paramref name="stream" />.
/// </summary>
/// <param name="stream">The stream of data to hash</param>
/// <returns>The hash of <paramref name="stream" />.</returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="stream" /> is null.</exception>
public byte[] Hash(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
using (var sha = new HMACSHA256(System.Text.Encoding.UTF8.GetBytes(_key)))
{
return sha.ComputeHash(stream);
}
}
}
} | 33.883333 | 123 | 0.557796 | [
"MIT"
] | ByteDev/ByteDev.Crypto | src/ByteDev.Crypto/Hashing/Algorithms/HmacSha256Algorithm.cs | 2,035 | C# |
#region Copyright (c) 2017 Leoxia Ltd
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="FileSystemInfoFactory.cs" company="Leoxia Ltd">
// Copyright (c) 2017 Leoxia Ltd
// </copyright>
//
// .NET Software Development
// https://www.leoxia.com
// Build. Tomorrow. Together
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// --------------------------------------------------------------------------------------------------------------------
#endregion
#region Usings
using Leoxia.Abstractions.IO;
#endregion
namespace Leoxia.Implementations.IO
{
/// <summary>
/// Factory for <see cref="IFileSystemInfo" />
/// </summary>
/// <seealso cref="Leoxia.Abstractions.IO.IFileSystemInfoFactory" />
public class FileSystemInfoFactory : IFileSystemInfoFactory
{
private readonly IDirectoryInfoFactory _directoryInfoFactory = new DirectoryInfoFactory();
private readonly IFileInfoFactory _fileInfoFactory = new FileInfoFactory();
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemInfoFactory" /> class.
/// </summary>
public FileSystemInfoFactory()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemInfoFactory" /> class.
/// </summary>
/// <param name="fileInfoFactory">The file information factory.</param>
/// <param name="directoryInfoFactory">The directory information factory.</param>
public FileSystemInfoFactory(IFileInfoFactory fileInfoFactory, IDirectoryInfoFactory directoryInfoFactory)
{
_fileInfoFactory = fileInfoFactory;
_directoryInfoFactory = directoryInfoFactory;
}
/// <summary>
/// Initializes a new instance of the <see cref="T:IFileSystemInfo" /> implementation, which acts as a wrapper for a
/// file path.
/// </summary>
/// <param name="fileName">
/// The fully qualified name of the new file or directory, or the relative file name or directory name. Do not end the
/// path with
/// the directory separator character.
/// </param>
/// <returns></returns>
public IFileSystemInfo Build(string fileName)
{
var fileInfo = _fileInfoFactory.Build(fileName);
if (fileInfo.Exists)
{
return fileInfo;
}
return _directoryInfoFactory.Build(fileName);
}
}
} | 40.76087 | 131 | 0.609333 | [
"MIT"
] | leoxialtd/Leoxia.Abstractions | src/Leoxia.Implementations.IO/FileSystemInfoFactory.cs | 3,752 | C# |
//-------------------------------------------------------------------------
// Copyright © 2019 Province of British Columbia
//
// 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.
//-------------------------------------------------------------------------
namespace HealthGateway.Common.Delegates
{
using System.Collections.Generic;
using System.Threading.Tasks;
using HealthGateway.Common.Models;
using HealthGateway.Common.Models.Immunization;
/// <summary>
/// Defines a delegate to retrieve immunization records.
/// </summary>
public interface IImmunizationDelegate
{
/// <summary>
/// Gets an immunization record for the given id.
/// </summary>
/// <param name="hdid">The hdid patient id.</param>
/// <param name="immunizationId">The immunization id.</param>
/// <returns>The immunization record with the given id.</returns>
Task<RequestResult<ImmunizationEvent>> GetImmunization(string hdid, string immunizationId);
}
}
| 41.216216 | 99 | 0.636066 | [
"Apache-2.0"
] | WadeBarnes/healthgateway | Apps/Common/src/Delegates/IImmunizationDelegate.cs | 1,528 | C# |
using System;
using Orchard.ContentManagement;
using Orchard.Tasks.Indexing;
namespace Orchard.Indexing.Models {
public class IndexingTask : IIndexingTask {
private readonly IContentManager _contentManager;
private readonly IndexingTaskRecord _record;
private ContentItem _item;
private bool _itemInitialized;
public IndexingTask(IContentManager contentManager, IndexingTaskRecord record) {
// in spite of appearances, this is actually a created class, not IoC,
// but dependencies are passed in for lazy initialization purposes
_contentManager = contentManager;
_record = record;
}
public DateTime? CreatedUtc {
get { return _record.CreatedUtc; }
}
public ContentItem ContentItem {
get {
if (!_itemInitialized) {
if (_record.ContentItemRecord != null) {
_item = _contentManager.Get(
_record.ContentItemRecord.Id, VersionOptions.Published);
}
_itemInitialized = true;
}
return _item;
}
}
}
} | 34.111111 | 88 | 0.585505 | [
"BSD-3-Clause"
] | 1996dylanriley/Orchard | src/Orchard.Web/Modules/Orchard.Indexing/Models/IndexingTask.cs | 1,228 | C# |
#if UNITY_2019_1_OR_NEWER
using UnityEditor;
namespace UnityAtoms.Editor
{
/// <summary>
/// Constant property drawer of type `GameObject`. Inherits from `AtomDrawer<GameObjectConstant>`. Only availble in `UNITY_2019_1_OR_NEWER`.
/// </summary>
[CustomPropertyDrawer(typeof(GameObjectConstant))]
public class GameObjectConstantDrawer : AtomDrawer<GameObjectConstant> { }
}
#endif
| 31.307692 | 150 | 0.7543 | [
"MIT"
] | sampaiodias/unity-atoms | Packages/Core/Editor/Drawers/Constants/GameObjectConstantDrawer.cs | 407 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// </copyright>
// <summary>Helper class to create projects for testing..</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
namespace Microsoft.Build.UnitTests.BackEnd
{
/// <summary>
/// Contains helper methods for creating projects for testing.
/// </summary>
internal static class ProjectHelpers
{
/// <summary>
/// Creates a project instance with a single empty target named 'foo'
/// </summary>
/// <returns>A project instance.</returns>
internal static ProjectInstance CreateEmptyProjectInstance()
{
XmlReader reader = XmlReader.Create(new StringReader
(
@"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='4.0'>
<Target Name='foo'/>
</Project>"
));
Project project = new Project(reader);
ProjectInstance instance = project.CreateProjectInstance();
return instance;
}
}
}
| 34 | 106 | 0.57754 | [
"MIT"
] | 0n1zz/main | src/Build.UnitTests/Definition/ProjectHelpers.cs | 1,498 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34014
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ListenScannerClient.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.645161 | 151 | 0.58473 | [
"Apache-2.0"
] | becker-portilla/ListenScanner | ListenScannerClient/Properties/Settings.Designer.cs | 1,076 | C# |
using System;
using System.Collections.Generic;
using System.Net.Http.Headers;
using KeyPayV2.Au.Models.Common;
using KeyPayV2.Au.Enums;
namespace KeyPayV2.Au.Models.Common
{
public class GetShiftsModel
{
public int? KioskId { get; set; }
public int? LocationId { get; set; }
public int? EmployeeId { get; set; }
public DateTime? FromDateUtc { get; set; }
public DateTime? ToDateUtc { get; set; }
}
}
| 26.166667 | 51 | 0.636943 | [
"MIT"
] | KeyPay/keypay-dotnet-v2 | src/keypay-dotnet/Au/Models/Common/GetShiftsModel.cs | 471 | C# |
namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
public interface IEventBus
{
void Publish(IntegrationEvent @event);
void Subscribe<T, TH>()
where T : IntegrationEvent
where TH : IIntegrationEventHandler<T>;
void SubscribeDynamic<TH>(string eventName)
where TH : IDynamicIntegrationEventHandler;
void UnsubscribeDynamic<TH>(string eventName)
where TH : IDynamicIntegrationEventHandler;
void Unsubscribe<T, TH>()
where TH : IIntegrationEventHandler<T>
where T : IntegrationEvent;
}
| 27.714286 | 76 | 0.719931 | [
"MIT"
] | 0x55xx5/eShopOnContainers | src/BuildingBlocks/EventBus/EventBus/Abstractions/IEventBus.cs | 584 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _8._5._1.prirucnik
{
public class Osoba
{
// deklaracija događaja
public delegate void NaPromjenuImenaDelegat(object sender, EventArgs e);
public event NaPromjenuImenaDelegat NaPromjenuImena;
// Svojstva
private string ime;
public string Ime
{
get { return ime; }
set
{
ime = value;
if(NaPromjenuImena != null)
{
NaPromjenuImena(this, new EventArgs());
}
}
}
}
}
| 20.114286 | 80 | 0.536932 | [
"MIT"
] | robertlucic66/AlgebraCSharp2019-1 | ConsoleApp1/8.5.1.prirucnik/Osoba.cs | 707 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Compute.V20190301.Outputs
{
[OutputType]
public sealed class ReplicationStatusResponse
{
/// <summary>
/// This is the aggregated replication status based on all the regional replication status flags.
/// </summary>
public readonly string AggregatedState;
/// <summary>
/// This is a summary of replication status for each region.
/// </summary>
public readonly ImmutableArray<Outputs.RegionalReplicationStatusResponse> Summary;
[OutputConstructor]
private ReplicationStatusResponse(
string aggregatedState,
ImmutableArray<Outputs.RegionalReplicationStatusResponse> summary)
{
AggregatedState = aggregatedState;
Summary = summary;
}
}
}
| 31.333333 | 105 | 0.677305 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Compute/V20190301/Outputs/ReplicationStatusResponse.cs | 1,128 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestaurantReviews.DataAccessLayer;
using RestaurantReviews.Library;
namespace RestaurantReviews.CRUD
{
class Client
{
static void Main(string[] args)
{
RestaurantHandler listRestaurants = new RestaurantHandler();
RestaurantCrud crud = new RestaurantCrud();
var restaurants = crud.LoadRestaurants();
foreach(var place in restaurants)
{
listRestaurants.AddRestaurant(place);
}
//crud.addRestaurant(listRestaurants);
foreach (Restaurant place in listRestaurants.restaurants)
{
place.displayInfo();
}
/*
string input;
Console.WriteLine("Enter a name or partial restaurant name to select");
input = Console.ReadLine().ToString();
listRestaurants.SelectRestaurant(input);
listRestaurants.AddReviewToThisRestaurant();
listRestaurants.DisplayTheseReviews();
*/
XMLSerialization restaurantXMLHandler = new XMLSerialization();
RestaurantHandler xmlRestaurantList;
xmlRestaurantList = restaurantXMLHandler.ReadListFromXML();
foreach (Restaurant place in xmlRestaurantList.restaurants)
{
listRestaurants.restaurants.Add(place);
}
foreach (Restaurant place in listRestaurants.restaurants)
{
place.displayInfo();
}
crud.addMultipleRestaurants(listRestaurants);
}
}
}
| 26.764706 | 83 | 0.574176 | [
"MIT"
] | 1804-Apr-USFdotnet/louis-wilson-project1 | RestaurantReviews.Library/RestaurantReviews.CRUD/Client.cs | 1,822 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
namespace AdvancedRenderPipeline.Runtime {
public static class ShaderTagManager {
#region ShaderTagIds
public static readonly ShaderTagId[] LEGACY_SHADER_TAGS = {
new ShaderTagId("Always"),
new ShaderTagId("ForwardBase"),
new ShaderTagId("PrepassBase"),
new ShaderTagId("Vertex"),
new ShaderTagId("VertexLMRGBM"),
new ShaderTagId("VertexLM")
};
public static readonly ShaderTagId NONE = ShaderTagId.none;
public static readonly ShaderTagId SRP_DEFAULT_UNLIT = new ShaderTagId("SRPDefaultUnlit");
public static readonly ShaderTagId DEPTH = new ShaderTagId("Depth");
public static readonly ShaderTagId OCCLUDER_DEPTH = new ShaderTagId("OccluderDepth");
public static readonly ShaderTagId MOTION_VECTORS = new ShaderTagId("MotionVectors");
public static readonly ShaderTagId SHADOW_CASTER = new ShaderTagId("ShadowCaster");
public static readonly ShaderTagId FORWARD = new ShaderTagId("Forward");
public static readonly ShaderTagId OPAQUE_FORWARD = new ShaderTagId("OpaqueForward");
#endregion
#region Shader Pass Names
public const string MOTION_VECTORS_PASS = "MotionVectors";
#endregion
}
}
| 33.184211 | 92 | 0.77954 | [
"MIT"
] | GuardHei/UltimateTAA | Assets/AdvancedRenderPipeline/Runtime/ShaderTagManager.cs | 1,261 | C# |
using UnityEngine;
namespace DefaultNamespace
{
public class MultiLineCacheTest
{
public void Test(Transform t)
{
t.position = t.position + t.position + t.posit{caret}ion;
var x = new Vector3(10, 0, 0);
x += new Vector3(0, 10, 10);
t.position = t.position + t.position;
}
}
} | 22 | 69 | 0.524064 | [
"Apache-2.0"
] | 20chan/resharper-unity | resharper/resharper-unity/test/data/CSharp/Intentions/QuickFixes/CachePropertyValue/MultiLineCacheTest.cs | 374 | C# |
using Microsoft.Extensions.Configuration;
using SharpRepository.Ioc.StructureMap.Factories;
using SharpRepository.Repository;
using SharpRepository.Repository.Configuration;
using StructureMap;
using StructureMap.Pipeline;
namespace SharpRepository.Ioc.StructureMap
{
public static class StructureMapExtensions
{
/// <summary>
/// Configures StructureMap container telling to resolve IRepository and ICompoundKeyRepository with the repository from configuration
/// </summary>
/// <param name="init"></param>
/// <param name="configuration"></param>
/// <param name="repositoryName">name of repository implementation in configuration, null tell to use default in configuration</param>
/// <param name="lifecycle">StructureMap coping of variables default is Lifecycle.Transient</param>
public static void ForRepositoriesUseSharpRepository(this ConfigurationExpression init, IConfigurationSection configurationSection, string repositoryName = null, ILifecycle lifeCycle = null)
{
if (configurationSection == null)
throw new ConfigurationErrorsException("Configuration section not found.");
var configuration = RepositoryFactory.BuildSharpRepositoryConfiguation(configurationSection);
init.ForRepositoriesUseSharpRepository(configuration, repositoryName, lifeCycle);
}
/// <summary>
/// Configures StructureMap container telling to resolve IRepository and ICompoundKeyRepository with the repository from configuration
/// </summary>
/// <param name="init"></param>
/// <param name="configuration"></param>
/// <param name="repositoryName">name of repository implementation in configuration, null tell to use default in configuration</param>
/// <param name="lifecycle">StructureMap coping of variables default is Lifecycle.Transient</param>
public static void ForRepositoriesUseSharpRepository(this ConfigurationExpression init, ISharpRepositoryConfiguration configuration, string repositoryName = null, ILifecycle lifeCycle = null)
{
if (lifeCycle == null)
{
lifeCycle = Lifecycles.Transient;
}
init.For(typeof(IRepository<>))
.LifecycleIs(lifeCycle)
.Use(new RepositoryNoKeyInstanceFactory(configuration, repositoryName));
init.For(typeof(IRepository<,>))
.LifecycleIs(lifeCycle)
.Use(new RepositorySingleKeyInstanceFactory(configuration, repositoryName));
init.For(typeof(ICompoundKeyRepository<,,>))
.LifecycleIs(lifeCycle)
.Use(new RepositoryDoubleKeyInstanceFactory(configuration, repositoryName));
init.For(typeof(ICompoundKeyRepository<,,,>))
.LifecycleIs(lifeCycle)
.Use(new RepositoryTripleKeyInstanceFactory(configuration, repositoryName));
init.For(typeof(ICompoundKeyRepository<>))
.LifecycleIs(lifeCycle)
.Use(new RepositoryCompoundKeyInstanceFactory(configuration, repositoryName));
}
}
}
| 47.895522 | 199 | 0.689935 | [
"Apache-2.0"
] | Magicianred/SharpRepository | SharpRepository.Ioc.StructureMap/StructureMapExtensions.cs | 3,211 | C# |
using System.ComponentModel.DataAnnotations;
namespace EmpowerData.EntityModels
{
public partial class CMS_PhoneType
{
[Key]
public int PhoneTypeSysID { get; set; }
[Required]
[StringLength(10)]
public string PhoneType { get; set; }
}
}
| 19.4 | 47 | 0.632302 | [
"Apache-2.0"
] | HaloImageEngine/EmpowerClaim-hotfix-1.25.1 | EmpowerData/EntityModels/CMS_PhoneType.cs | 291 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using Elsa.Scripting.CSharp.Services;
using Elsa.Services;
using Elsa.Services.Models;
using Fluid;
using Fluid.Values;
namespace Elsa.Scripting.CSharp.Filters
{
public class WorkflowDefinitionIdFilter : ICSharpFilter
{
private readonly IWorkflowRegistry _workflowRegistry;
public WorkflowDefinitionIdFilter(IWorkflowRegistry workflowRegistry) => _workflowRegistry = workflowRegistry;
public async ValueTask<FluidValue> ProcessAsync(FluidValue input, FilterArguments arguments, TemplateContext context)
{
var queryType = arguments.Values?.FirstOrDefault()?.ToStringValue() ?? "name";
var queryValue = input.ToStringValue().ToLowerInvariant();
Func<IWorkflowBlueprint, bool> predicate = queryType switch
{
"name" => x => string.Equals(x.Name, queryValue, StringComparison.OrdinalIgnoreCase),
"tag" => x => string.Equals(x.Tag, queryValue, StringComparison.OrdinalIgnoreCase),
_ => throw new ArgumentOutOfRangeException()
};
var workflowBlueprint = await _workflowRegistry.FindAsync(predicate);
var workflowDefinitionId = workflowBlueprint?.Id;
return new StringValue(workflowDefinitionId);
}
}
} | 38.828571 | 125 | 0.695364 | [
"MIT"
] | g10101k/elsa-core | src/scripting/Elsa.Scripting.CSharp/Filters/WorkflowDefinitionIdFilter.cs | 1,361 | C# |
using Azure.Messaging.EventGrid;
using Demo.Infrastructure.Events;
using Demo.WebApi.Auth;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace Demo.WebApi.Controllers
{
public class EventsController : ApiControllerBase
{
[HttpPost]
[Authorize(nameof(Policies.Machine))]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(ProblemDetails), (int)HttpStatusCode.InternalServerError)]
public async Task<ActionResult> Post([FromBody] EventGridEvent[] eventGridEvents, CancellationToken cancellationToken)
{
var @events = eventGridEvents.Select(eventGridEvent => eventGridEvent.ToEvent());
foreach (var @event in @events)
{
await Mediator.Publish(@event, cancellationToken);
}
return Ok();
}
}
}
| 30.78125 | 126 | 0.691371 | [
"MIT"
] | nvdvlies/dotnet-api-and-angular-frontend-modular-monolith | src/Demo.WebApi/Controllers/EventsController.cs | 987 | C# |
using System.Collections.ObjectModel;
using Myra.Attributes;
using Newtonsoft.Json;
#if !XENKO
using Microsoft.Xna.Framework;
#else
using Xenko.Core.Mathematics;
#endif
namespace Myra.Graphics2D.UI
{
public class MenuItem : ListItem, IMenuItemsContainer, IMenuItem
{
private readonly ObservableCollection<IMenuItem> _items = new ObservableCollection<IMenuItem>();
[HiddenInEditor]
[JsonIgnore]
public Menu Menu { get; set; }
[HiddenInEditor]
public ObservableCollection<IMenuItem> Items
{
get { return _items; }
}
[HiddenInEditor]
[JsonIgnore]
public bool Enabled
{
get { return Widget != null && Widget.Enabled; }
set { Widget.Enabled = value; }
}
[HiddenInEditor]
[JsonIgnore]
public char? UnderscoreChar
{
get
{
var button = (MenuItemButton)Widget;
return button.UnderscoreChar;
}
}
public MenuItem(string id, string text, Color? color, object tag) : base(text, color, tag)
{
Id = id;
}
public MenuItem(string id, string text, Color? color) : this(id, text, color, null)
{
}
public MenuItem(string id, string text) : this(id, text, null)
{
}
public MenuItem(string id) : this(id, string.Empty)
{
}
public MenuItem() : this(string.Empty)
{
}
internal MenuItem FindMenuItemById(string id)
{
if (Id == id)
{
return this;
}
foreach (var item in _items)
{
var asMenuItem = item as MenuItem;
if (asMenuItem == null)
{
continue;
}
var result = asMenuItem.FindMenuItemById(id);
if (result != null)
{
return result;
}
}
return null;
}
}
} | 17.419355 | 98 | 0.653704 | [
"MIT"
] | Genobreaker/Myra | src/Myra/Graphics2D/UI/MenuItem.cs | 1,622 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Tarea32
{
public partial class FRMMAYMEN : Form
{
public FRMMAYMEN()
{
InitializeComponent();
}
private void Captura_Click(object sender, EventArgs e)
{
//Programa de adivinanza de numeros
//Silva Reyes Luis Adrian 19210549
//Tarea#32
//Declaracion de variables
int N = 10;
int Num ;
int C = 0;
//Crea un objeto de la clase FRMSEGUNDA
FRMSEGUNDA FormaCaptura = new FRMSEGUNDA();
if (FormaCaptura.ShowDialog() == DialogResult.OK)
{
//Do-While
do
{
Num = Convert.ToInt32(FormaCaptura.TXTNUM.Text);
FormaCaptura.TXTNUM.Text = Num.ToString();
if (Num > N)
{
TXTNUM.Text = TXTNUM.Text + "Es mayor:"+Num + "\r\n";
}
if (Num < N)
{
TXTNUM.Text = TXTNUM.Text + "Es menor:" + Num + "\r\n";
}
if (Num == 10)
{
TXTMAYMEN.Text = TXTMAYMEN.Text + "Felecidades,ganaste" + "\r\n";
}
else
{
TXTMAYMEN.Text = TXTMAYMEN.Text + "Perdiste" + "\r\n";
}
//Contador
C = C + 1;
} while ( C<1);
if(C<=5)
{
LBLA.Text = "Bueno";
}
else if(C>5 && C<=15)
{
LBLA.Text = "Regular";
}
else
{
LBLA.Text = "Malo";
}
}
}
private void CMDOTRO_Click(object sender, EventArgs e)
{
TXTNUM.Clear();
TXTMAYMEN.Clear();
TXTNUM.Focus();
}
private void Salida_Click(object sender, EventArgs e)
{
Close();
}
}
}
| 23.084112 | 89 | 0.392308 | [
"Apache-2.0"
] | Luissf1/Programas-C- | Tarea32/Tarea32/Form1.cs | 2,472 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Reflection;
using OpenQA.Selenium;
using Xunit.Sdk;
namespace Blazorise.E2ETests.Infrastructure
{
// This has to use BeforeAfterTestAttribute because running the log capture
// in the BrowserFixture.Dispose method is too late, and we can't add logging
// to the test.
public class CaptureSeleniumLogsAttribute : BeforeAfterTestAttribute
{
public override void Before(MethodInfo methodUnderTest)
{
if (!typeof(BrowserTestBase).IsAssignableFrom(methodUnderTest.DeclaringType))
{
throw new InvalidOperationException("This should only be used with BrowserTestBase");
}
}
public override void After(MethodInfo methodUnderTest)
{
var logs = BrowserTestBase.Logs;
var output = BrowserTestBase.Output;
// Put browser logs first, the test UI will truncate output after a certain length
// and the browser logs will include exceptions thrown by js in the browser.
foreach (var kind in logs.AvailableLogTypes.OrderBy(k => k == LogType.Browser ? 0 : 1))
{
output.WriteLine($"{kind} Logs from Selenium:");
var entries = logs.GetLog(kind);
foreach (LogEntry entry in entries)
{
output.WriteLine($"[{entry.Timestamp}] - {entry.Level} - {entry.Message}");
}
output.WriteLine("");
output.WriteLine("");
}
}
}
}
| 35.816327 | 111 | 0.621083 | [
"Apache-2.0"
] | Luk164/Blazorise | Tests/Blazorise.E2ETests/Infrastructure/CaptureSeleniumLogsAttribute.cs | 1,757 | C# |
using TeamSpark.AzureDay.WebSite.Data.Entity.Table;
namespace TeamSpark.AzureDay.WebSite.Data.Service.Table
{
public class CouponService : TableServiceBase<Coupon>
{
protected override string TableName
{
get { return "Coupon"; }
}
public CouponService(string accountName, string accountKey)
: base(accountName, accountKey)
{
}
}
}
| 19.722222 | 61 | 0.740845 | [
"MIT"
] | AzureDay/2016-WebSite | TeamSpark.AzureDay.WebSite.Data/Service/Table/CouponService.cs | 357 | C# |
//----------------------------------------------
// Flip Web Apps: Beautiful Transitions
// Copyright © 2016 Flip Web Apps / Mark Hewitt
//
// Please direct any bugs/comments/suggestions to http://www.flipwebapps.com
//
// The copyright owner grants to the end user a non-exclusive, worldwide, and perpetual license to this Asset
// to integrate only as incorporated and embedded components of electronic games and interactive media and
// distribute such electronic game and interactive media. End user may modify Assets. End user may otherwise
// not reproduce, distribute, sublicense, rent, lease or lend the Assets. It is emphasized that the end
// user shall not be entitled to distribute or transfer in any way (including, without, limitation by way of
// sublicense) the Assets in any other way than as integrated components of electronic games and interactive media.
// The above copyright notice and this permission notice must not be removed from any files.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//----------------------------------------------
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
namespace BeautifulTransitions.Scripts.Shake.Components {
/// <summary>
/// Component to shake the camera with specified settings.
/// </summary>
/// ShakeCamera is a singleton component and so only one instance can exist in your scene. For simplicity you can access
/// this component through ShakeCamera.Instance
[AddComponentMenu("Beautiful Transitions/Shake/Shake Camera")]
[HelpURL("http://www.flipwebapps.com/beautiful-transitions/shake/")]
public class ShakeCamera : MonoBehaviour
{
#region Singleton
// Static singleton property
public static ShakeCamera Instance { get; private set; }
public static bool IsActive { get { return Instance != null; } }
void Awake()
{
// First we check if there are any other instances conflicting then destroy this and return
if (Instance != null)
{
if (Instance != this)
Destroy(gameObject);
return; // return is my addition so that the inspector in unity still updates
}
// Here we save our singleton instance
Instance = this as ShakeCamera;
// setup specifics for instantiated object only.
Setup();
}
void OnDestroy()
{
// cleanup for instantiated object only.
if (Instance == this) { }
}
#endregion Singleton
/// <summary>
/// The cameras to shake. If blank then either then a Camera on this gameobject or the main camera will be used instead.
/// </summary>
[Tooltip("A list of cameras to shake. If left empty cameras on the same gameobject as the component will be used, or if none are found the main camera.")]
public List<Camera> Cameras;
/// <summary>
/// The duration to shake the camera for.
/// </summary>
[Tooltip("The duration to shake the camera for.")]
public float Duration = 1f;
/// <summary>
/// The offset after which to start decaying (slowing down) the movement.
/// </summary>
[Tooltip("The offset relative to duration after which to start decaying (slowing down) the movement in the range 0 to 1.")]
[Range(0, 1)]
public float DecayStart = 0.75f;
/// <summary>
/// The shake movement range from the origin. Set any dimension to 0 to stop movement along that axis.
/// </summary>
[Tooltip("The shake movement range from the origin. Set any dimension to 0 to stop movement along that axis.")]
public Vector3 Range = Vector3.one;
/// <summary>
/// Setup the cameras - called by Awake
/// </summary>
void Setup()
{
if (Cameras.Count < 1)
{
if (GetComponent<Camera>())
Cameras.Add(GetComponent<Camera>());
if (Cameras.Count < 1)
{
if (Camera.main)
Cameras.Add(Camera.main);
}
}
Assert.AreNotEqual(0, Cameras.Count, "No Cameras assigned and not able to find any!");
}
/// <summary>
/// Start shaking the cameras.
/// </summary>
public void Shake()
{
Shake(Duration, Range, DecayStart);
}
/// <summary>
/// Start shaking the cameras.
/// </summary>
public void Shake(float duration, Vector3 range, float decayStart)
{
foreach (var targetCamera in Cameras)
{
ShakeHelper.Shake(this, targetCamera.transform, duration, range, decayStart);
}
}
}
} | 41.636364 | 163 | 0.598617 | [
"MIT"
] | Kaiweitu/eecs494_p3 | Assets/FlipWebApps/BeautifulTransitions/Scripts/Shake/Components/ShakeCamera.cs | 5,499 | C# |
using System;
namespace SampleProject
{
/// <summary>
/// Test
/// <code language="csharp">// This is sample code</code>
/// </summary>
public class ExampleClass
{
public int Id { get; set; }
/// <summary>
/// Gets a sample name
/// </summary>
/// <param name="firstName">The person's first name</param>
/// <param name="lastName">The person's last name</param>
/// <param name="middleNames">A <see cref="T:string[]"/> of all the person's middle names</param>
/// <returns>The name of the current person as a single <see cref="String"/></returns>
/// <remarks>Puts a space between each name. <see cref="ExampleNamespace.SampleClass"/> is not used</remarks>
/// <example>
/// A person with two middle names:
/// <code language="lang-csharp">
/// var example = new ExampleClass();
/// var fullName = example.GetFullName("John", "Smith", "David", "James");
///
/// // Output: "John David James Smith"
/// Console.WriteLine(fullName);
/// </code>
///
/// A person with no middle names:
/// <code language="lang-csharp">
/// var example = new ExampleClass();
/// var fullName = example.GetFullName("Daniel", "Jones");
///
/// // Output: Daniel Jones
/// Console.WriteLine(fullName);
/// </code>
/// </example>
/// <exception cref="NotImplementedException">This method is not yet implemented</exception>
public string GetFullName(string firstName, string lastName, params string[] middleNames)
{
throw new NotImplementedException();
}
}
}
| 36.914894 | 117 | 0.560231 | [
"MIT"
] | MarkSFrancis/DocsGenerator | Sample/SampleProject/ExampleClass.cs | 1,737 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20190701.Inputs
{
/// <summary>
/// SKU of a public IP address.
/// </summary>
public sealed class PublicIPAddressSkuArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Name of a public IP address SKU.
/// </summary>
[Input("name")]
public InputUnion<string, Pulumi.AzureNative.Network.V20190701.PublicIPAddressSkuName>? Name { get; set; }
public PublicIPAddressSkuArgs()
{
}
}
}
| 27.655172 | 114 | 0.658354 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Network/V20190701/Inputs/PublicIPAddressSkuArgs.cs | 802 | C# |
using System;
using System.Collections.Generic;
using Calamari.Common.Plumbing.ServiceMessages;
using Calamari.Testing.LogParser;
namespace Calamari.Testing
{
public class TestCalamariCommandResult
{
public TestCalamariCommandResult(int exitCode, IReadOnlyDictionary<string, TestOutputVariable> outputVariables,
IReadOnlyList<TestScriptOutputAction> outputActions, IReadOnlyList<ServiceMessage> serviceMessages,
string? resultMessage, IReadOnlyList<CollectedArtifact> artifacts, string fullLog, string workingPath)
{
ExitCode = exitCode;
OutputVariables = outputVariables;
OutputActions = outputActions;
ServiceMessages = serviceMessages;
ResultMessage = resultMessage;
FullLog = fullLog;
WorkingPath = workingPath;
Artifacts = artifacts;
}
public string FullLog { get; }
public string WorkingPath { get; }
public IReadOnlyList<CollectedArtifact> Artifacts { get; }
public IReadOnlyDictionary<string, TestOutputVariable> OutputVariables { get; }
public IReadOnlyList<TestScriptOutputAction> OutputActions { get; }
public IReadOnlyList<ServiceMessage> ServiceMessages { get; }
public TestExecutionOutcome Outcome => WasSuccessful ? TestExecutionOutcome.Successful : TestExecutionOutcome.Unsuccessful;
public bool WasSuccessful => ExitCode == 0;
public string? ResultMessage { get; }
public int ExitCode { get; }
}
} | 43.166667 | 131 | 0.701416 | [
"Apache-2.0"
] | OctopusDeploy/Calamari | source/Calamari.Testing/TestCalamariCommandResult.cs | 1,556 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace ByteBank.Funcionarios {
class GerenteDeConta : Funcionario {
public GerenteDeConta(string cpf) : base(cpf, 4000) {
}
public override void AumentarSalario() {
Salario *= 1.05;
}
public override double GetBonificacao() {
return Salario * 0.25;
}
}
}
| 22.473684 | 62 | 0.578454 | [
"MIT"
] | alan1tavares/labs | DotNet/Alura/Excessoes/01-ByteBank/Funcionarios/GerenteDeConta.cs | 429 | C# |
using System;
using NetOffice;
namespace NetOffice.OutlookApi.Enums
{
/// <summary>
/// SupportByVersion Outlook 12, 14, 15
/// </summary>
[SupportByVersionAttribute("Outlook", 12,14,15)]
[EntityTypeAttribute(EntityType.IsEnum)]
public enum OlContextMenu
{
/// <summary>
/// SupportByVersion Outlook 12, 14, 15
/// </summary>
/// <remarks>0</remarks>
[SupportByVersionAttribute("Outlook", 12,14,15)]
olItemContextMenu = 0,
/// <summary>
/// SupportByVersion Outlook 12, 14, 15
/// </summary>
/// <remarks>1</remarks>
[SupportByVersionAttribute("Outlook", 12,14,15)]
olViewContextMenu = 1,
/// <summary>
/// SupportByVersion Outlook 12, 14, 15
/// </summary>
/// <remarks>2</remarks>
[SupportByVersionAttribute("Outlook", 12,14,15)]
olFolderContextMenu = 2,
/// <summary>
/// SupportByVersion Outlook 12, 14, 15
/// </summary>
/// <remarks>3</remarks>
[SupportByVersionAttribute("Outlook", 12,14,15)]
olAttachmentContextMenu = 3,
/// <summary>
/// SupportByVersion Outlook 12, 14, 15
/// </summary>
/// <remarks>4</remarks>
[SupportByVersionAttribute("Outlook", 12,14,15)]
olStoreContextMenu = 4,
/// <summary>
/// SupportByVersion Outlook 12, 14, 15
/// </summary>
/// <remarks>5</remarks>
[SupportByVersionAttribute("Outlook", 12,14,15)]
olShortcutContextMenu = 5
}
} | 26.759259 | 52 | 0.618685 | [
"MIT"
] | NetOffice/NetOffice | Source/Outlook/Enums/OlContextMenu.cs | 1,445 | C# |
//
// C4Listener_native_ios.cs
//
// Copyright (c) 2018 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Linq;
using System.Runtime.InteropServices;
using LiteCore.Util;
namespace LiteCore.Interop
{
internal unsafe static partial class Native
{
[DllImport(Constants.DllNameIos, CallingConvention = CallingConvention.Cdecl)]
public static extern C4ListenerAPIs c4listener_availableAPIs();
[DllImport(Constants.DllNameIos, CallingConvention = CallingConvention.Cdecl)]
public static extern C4Listener* c4listener_start(C4ListenerConfig* config, C4Error* error);
[DllImport(Constants.DllNameIos, CallingConvention = CallingConvention.Cdecl)]
public static extern void c4listener_free(C4Listener* listener);
public static bool c4listener_shareDB(C4Listener* listener, string name, C4Database* db)
{
using(var name_ = new C4String(name)) {
return NativeRaw.c4listener_shareDB(listener, name_.AsFLSlice(), db);
}
}
public static bool c4listener_unshareDB(C4Listener* listener, string name)
{
using(var name_ = new C4String(name)) {
return NativeRaw.c4listener_unshareDB(listener, name_.AsFLSlice());
}
}
public static string c4db_URINameFromPath(string path)
{
using(var path_ = new C4String(path)) {
using(var retVal = NativeRaw.c4db_URINameFromPath(path_.AsFLSlice())) {
return ((FLSlice)retVal).CreateString();
}
}
}
}
internal unsafe static partial class NativeRaw
{
[DllImport(Constants.DllNameIos, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U1)]
public static extern bool c4listener_shareDB(C4Listener* listener, FLSlice name, C4Database* db);
[DllImport(Constants.DllNameIos, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U1)]
public static extern bool c4listener_unshareDB(C4Listener* listener, FLSlice name);
[DllImport(Constants.DllNameIos, CallingConvention = CallingConvention.Cdecl)]
public static extern FLSliceResult c4db_URINameFromPath(FLSlice path);
}
}
| 35.62963 | 105 | 0.692308 | [
"Apache-2.0"
] | lore-coolshop/couchbase-lite-net | src/LiteCore/src/LiteCore.Shared/Interop/iOS/C4Listener_native_ios.cs | 2,886 | C# |
/* ***************************************************************************
Copyright (c): 2013 Hericus Software, Inc.
License: The MIT License (MIT)
Authors: Steven M. Cherry
*************************************************************************** */
using System;
using System.Threading;
namespace Helix.Glob
{
/// <summary>
/// This class represents a single log message. All of the fields that
/// we log are here as member variables. This allows us to store log messages
/// before writing them out to disk if that is what we want to do.
/// </summary>
public class LogMsg
{
public static string StaticAppName = null;
public static string StaticMachineName = null;
/// <summary>
/// Standard Constructor
/// </summary>
public LogMsg ()
{
tid = Thread.CurrentThread.ManagedThreadId;
SetTimestamp ();
SetAppMachine ();
id = 0;
line = 0;
channel = 0;
appName = StaticAppName;
machineName = StaticMachineName;
msg_static = false;
}
/// <summary>
/// Construct a log message with no application or transaction.
/// </summary>
/// <param name="f">File.</param>
/// <param name="l">Line.</param>
/// <param name="message">Message.</param>
public LogMsg(string f, int l, string message)
{
tid = Thread.CurrentThread.ManagedThreadId;
SetTimestamp ();
SetAppMachine ();
id = 0;
file = f;
line = l;
channel = 0;
msg = message;
appName = StaticAppName;
machineName = StaticMachineName;
msg_static = false;
}
/// <summary>
/// Construct a log message with just file and line.
/// </summary>
/// <param name="f">File.</param>
/// <param name="l">Line.</param>
public LogMsg(string f, int l)
{
tid = Thread.CurrentThread.ManagedThreadId;
SetTimestamp ();
SetAppMachine ();
id = 0;
file = f;
line = l;
channel = 0;
appName = StaticAppName;
machineName = StaticMachineName;
msg_static = false;
}
/// <summary>
/// A unique id for this log message
/// </summary>
public int id;
/// <summary>
/// Source File name of the log message
/// </summary>
public string file;
/// <summary>
/// Source File Line number of the log message
/// </summary>
public int line;
/// <summary>
/// Thread ID of the creator of this log message
/// </summary>
public int tid;
/// <summary>
/// Timestamp of the time of this log message
/// </summary>
public DateTime timestamp;
/// <summary>
/// A Specific log channel
/// </summary>
public int channel;
/// <summary>
/// An application name
/// </summary>
public string appName;
/// <summary>
/// A machine name for where the log originated
/// </summary>
public string machineName;
/// <summary>
/// An application specific unique id - usually like a session or connection token
/// </summary>
public string appSession;
/// <summary>
/// The actual log message
/// </summary>
public string msg;
/// <summary>
/// Whether this message is a static string or not.
/// </summary>
public bool msg_static;
/// <summary>
/// Sets the timestamp to right now.
/// </summary>
public void SetTimestamp()
{
timestamp = DateTime.Now;
}
/// <summary>
/// Handles determining our application and machine name.
/// </summary>
public void SetAppMachine()
{
if (StaticMachineName == null) {
StaticMachineName = System.Diagnostics.Process.GetCurrentProcess ().MachineName;
}
if (StaticAppName == null) {
StaticAppName = System.Diagnostics.Process.GetCurrentProcess ().MainModule.ModuleName;
}
}
/// <summary>
/// Formats our timestamp in a standard way and returns it.
/// </summary>
/// <returns>The timestamp.</returns>
public string GetTimestamp()
{
return String.Format ("{0:yyyy/MM/dd HH:mm:ss.fff}", timestamp);
}
}
}
| 22.358382 | 90 | 0.610134 | [
"MIT"
] | smc314/helix | server/net/glob/LogMsg.cs | 3,870 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
namespace Microsoft.MixedReality.Toolkit.Core.Interfaces.InputSystem
{
/// <summary>
/// Provides eye tracking information.
/// </summary>
public interface IMixedRealityEyeSaccadeProvider : IMixedRealityDataProvider
{
/// <summary>
/// Triggered when user is saccading across the view (jumping quickly with their eye gaze above a certain threshold in visual angles).
/// </summary>
event Action OnSaccade;
/// <summary>
/// Triggered when user is saccading horizontally across the view (jumping quickly with their eye gaze above a certain threshold in visual angles).
/// </summary>
event Action OnSaccadeX;
/// <summary>
/// Triggered when user is saccading vertically across the view (jumping quickly with their eye gaze above a certain threshold in visual angles).
/// </summary>
event Action OnSaccadeY;
}
} | 39.535714 | 156 | 0.682023 | [
"MIT"
] | Bhaskers-Blu-Org2/GalaxyExplorer | Assets/MixedRealityToolkit/Interfaces/InputSystem/IMixedRealityEyeSaccadeProvider.cs | 1,109 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Apartmant.Database.ApartmentDataSetTableAdapters;
namespace Apartment.UserInterface.Room
{
public partial class AddRoomTypeUI : Form
{
public int RoomTypeID
{
get;
set;
}
public AddRoomTypeUI()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
if (RoomTypeID == 0)
{
try
{
RoomTypesTableAdapter roomTypesTableAdapter = new RoomTypesTableAdapter();
roomTypesTableAdapter.Insert(
tbxRoomTypeName.Text.Trim(),
Convert.ToInt32(cbxCustomerType.SelectedValue),
Convert.ToDouble(tbxPrice.Text),
tbxDescription.Text.Trim());
MessageBox.Show("บันทึกเสร็จสมบูรณ์");
DialogResult = System.Windows.Forms.DialogResult.Yes;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
MessageBox.Show("ไม่สามารถบันทึกได้");
DialogResult = System.Windows.Forms.DialogResult.No;
throw;
}
}
else
{
try
{
this.roomTypesBindingSource.EndEdit();
this.roomTypesTableAdapter.Update(this.apartmentDataSet.RoomTypes);
MessageBox.Show("บันทึกเสร็จสมบูรณ์");
this.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
MessageBox.Show("ไม่สามารถบันทึกได้");
DialogResult = System.Windows.Forms.DialogResult.No;
throw;
}
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
DialogResult = System.Windows.Forms.DialogResult.No;
}
private void AddRoomTypeUI_Load(object sender, EventArgs e)
{
this.customerTypesTableAdapter.Fill(this.apartmentDataSet.CustomerTypes);
if (RoomTypeID != 0)
{
this.roomTypesTableAdapter.FillByID(this.apartmentDataSet.RoomTypes, RoomTypeID);
cbxCustomerType.Enabled = false;
tbxRoomTypeName.ReadOnly = true;
tbxPrice.ReadOnly = true;
}
}
}
}
| 31.280899 | 97 | 0.509339 | [
"MIT"
] | isman-usoh/apament-management-system | Apartmant/UserInterface/Room/AddRoomTypeUI.cs | 2,930 | C# |
namespace Csla.Analyzers.Tests.Targets.IsOperationMethodPublicAnalyzerTests
{
public class AnalyzeWhenTypeIsNotStereotype
{
public void DataPortal_Fetch() { }
}
} | 24.714286 | 76 | 0.791908 | [
"MIT"
] | angtianqiang/csla | Source/Csla.Analyzers/Csla.Analyzers.Tests/Targets/IsOperationMethodPublicAnalyzerTests/AnalyzeWhenTypeIsNotStereotype.cs | 175 | C# |
using System.Resources;
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("Contracts")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Contracts")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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")]
| 34.612903 | 84 | 0.742777 | [
"MIT"
] | fpommerening/Spartakiade2017-RabbitMQ | Samples/IoT/src/ContractsPortable/Properties/AssemblyInfo.cs | 1,076 | C# |
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
* Copyright (c) 2017-2019 Swan & The Quaver Team <support@quavergame.com>.
*/
using System;
using System.Collections.Generic;
using MoonSharp.Interpreter;
using MoonSharp.Interpreter.Interop;
using Quaver.API.Enums;
using YamlDotNet.Serialization;
namespace Quaver.API.Maps.Structures
{
/// <summary>
/// TimingPoints section of the .qua
/// </summary>
[Serializable]
[MoonSharpUserData]
public class TimingPointInfo
{
/// <summary>
/// The time in milliseconds for when this timing point begins
/// </summary>
public float StartTime
{
get;
[MoonSharpVisible(false)] set;
}
/// <summary>
/// The BPM during this timing point
/// </summary>
public float Bpm
{
get;
[MoonSharpVisible(false)] set;
}
/// <summary>
/// The signature during this timing point
/// </summary>
public TimeSignature Signature
{
get;
[MoonSharpVisible(false)] set;
}
/// <summary>
/// Whether timing lines during this timing point should be hidden or not
/// </summary>
public bool Hidden
{
get;
[MoonSharpVisible(false)] set;
}
[YamlIgnore]
public bool IsEditableInLuaScript
{
get;
[MoonSharpVisible(false)] set;
}
/// <summary>
/// The amount of milliseconds per beat this one takes up.
/// </summary>
[YamlIgnore]
public float MillisecondsPerBeat => 60000 / Bpm;
/// <summary>
/// By-value comparer, auto-generated by Rider.
/// </summary>
private sealed class ByValueEqualityComparer : IEqualityComparer<TimingPointInfo>
{
public bool Equals(TimingPointInfo x, TimingPointInfo y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
if (x.GetType() != y.GetType()) return false;
return x.StartTime.Equals(y.StartTime) && x.Bpm.Equals(y.Bpm) && x.Signature == y.Signature && x.Hidden == y.Hidden;
}
public int GetHashCode(TimingPointInfo obj)
{
unchecked
{
var hashCode = obj.StartTime.GetHashCode();
hashCode = (hashCode * 397) ^ obj.Bpm.GetHashCode();
hashCode = (hashCode * 397) ^ (int) obj.Signature;
hashCode = (hashCode * 397) ^ (obj.Hidden ? 1 : 0);
return hashCode;
}
}
}
public static IEqualityComparer<TimingPointInfo> ByValueComparer { get; } = new ByValueEqualityComparer();
}
} | 30.970588 | 132 | 0.541944 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | IceDynamix/Quaver.API | Quaver.API/Maps/Structures/TimingPointInfo.cs | 3,159 | C# |
// *******************************************************************************
// <copyright file="LocationFilter.cs" company="Intuit">
// Copyright (c) 2019 Intuit
//
// 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.
//
// </copyright>
// *******************************************************************************
namespace Intuit.TSheets.Model.Filters
{
using System;
using System.Collections.Generic;
using Intuit.TSheets.Client.Serialization.Converters;
using Intuit.TSheets.Model.Enums;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using NJsonSchema;
using NJsonSchema.Annotations;
/// <summary>
/// Filter for narrowing down the results of a call to retrieve <see cref="Location"/> entities.
/// </summary>
[JsonObject]
public class LocationFilter : EntityFilter
{
/// <summary>
/// Gets or sets the location ids you'd like to filter on.
/// </summary>
/// <remarks>
/// If omitted, all locations matching other specified filters are returned.
/// </remarks>
[JsonConverter(typeof(EnumerableToCsvConverter))]
[JsonSchema(JsonObjectType.String)]
[JsonProperty("ids")]
public IEnumerable<int> Ids { get; set; }
/// <summary>
/// Gets or sets the value for filtering by active or inactive state, or both.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
[JsonProperty("active")]
public TristateChoice? Active { get; set; }
/// <summary>
/// Gets or sets the geocoding statuses you'd like to filter on.
/// </summary>
/// <remarks>
/// If omitted, all locations matching other specified filters are returned.
/// </remarks>
[JsonConverter(typeof(StringEnumConverter))]
[JsonProperty("geocoding_status")]
public GeocodingStatus? GeocodingStatus { get; set; }
/// <summary>
/// Gets or sets the filter for returning only those locations modified before this date/time.
/// </summary>
[JsonConverter(typeof(DateTimeFormatConverter))]
[JsonProperty("modified_before")]
public DateTimeOffset? ModifiedBefore { get; set; }
/// <summary>
/// Gets or sets the filter for returning only those locations modified after this date/time.
/// </summary>
[JsonConverter(typeof(DateTimeFormatConverter))]
[JsonProperty("modified_since")]
public DateTimeOffset? ModifiedSince { get; set; }
/// <summary>
/// Gets or sets the value indicating whether to filter by jobcode assignment.
/// </summary>
/// <remarks>
/// If specified, only locations mapped to a jobcode the user is assigned to will be returned.
/// </remarks>
[JsonProperty("by_jobcode_assignment")]
public bool? ByJobcodeAssignment { get; set; }
}
}
| 38.865169 | 102 | 0.618098 | [
"Apache-2.0"
] | lisashort/TSheets-V1-DotNET-SDK | Intuit.TSheets/Model/Filters/LocationFilter.cs | 3,461 | C# |
using System;
namespace UCS.Core.Crypto.TweetNaCl
{
public class curve25519xsalsa20poly1305
{
public const int crypto_secretbox_PUBLICKEYBYTES = 32;
public const int crypto_secretbox_SECRETKEYBYTES = 32;
public const int crypto_secretbox_BEFORENMBYTES = 32;
public const int crypto_secretbox_NONCEBYTES = 24;
public const int crypto_secretbox_ZEROBYTES = 32;
public const int crypto_secretbox_BOXZEROBYTES = 16;
public static int crypto_box_getpublickey(byte[] pk, byte[] sk)
{
return curve25519.crypto_scalarmult_base(pk, sk);
}
public static int crypto_box_keypair(byte[] pk, byte[] sk)
{
new Random().NextBytes(sk);
return curve25519.crypto_scalarmult_base(pk, sk);
}
public static int crypto_box_afternm(byte[] c, byte[] m, long mlen, byte[] n, byte[] k)
{
return xsalsa20poly1305.crypto_secretbox(c, m, mlen, n, k);
}
public static int crypto_box_beforenm(byte[] k, byte[] pk, byte[] sk)
{
byte[] s = new byte[32];
byte[] sp = s, sigmap = xsalsa20.sigma;
curve25519.crypto_scalarmult(sp, sk, pk);
return hsalsa20.crypto_core(k, null, sp, sigmap);
}
public static int crypto_box(byte[] c, byte[] m, long mlen, byte[] n, byte[] pk, byte[] sk)
{
byte[] k = new byte[crypto_secretbox_BEFORENMBYTES];
byte[] kp = k;
crypto_box_beforenm(kp, pk, sk);
return crypto_box_afternm(c, m, mlen, n, kp);
}
public static int crypto_box_open(byte[] m, byte[] c, long clen, byte[] n, byte[] pk, byte[] sk)
{
byte[] k = new byte[crypto_secretbox_BEFORENMBYTES];
byte[] kp = k;
crypto_box_beforenm(kp, pk, sk);
return crypto_box_open_afternm(m, c, clen, n, kp);
}
public static int crypto_box_open_afternm(byte[] m, byte[] c, long clen, byte[] n, byte[] k)
{
return xsalsa20poly1305.crypto_secretbox_open(m, c, clen, n, k);
}
public static int crypto_box_afternm(byte[] c, byte[] m, byte[] n, byte[] k)
{
byte[] cp = c, mp = m, np = n, kp = k;
return crypto_box_afternm(cp, mp, (long) m.Length, np, kp);
}
public static int crypto_box_open_afternm(byte[] m, byte[] c, byte[] n, byte[] k)
{
byte[] cp = c, mp = m, np = n, kp = k;
return crypto_box_open_afternm(mp, cp, (long) c.Length, np, kp);
}
public static int crypto_box(byte[] c, byte[] m, byte[] n, byte[] pk, byte[] sk)
{
byte[] cp = c, mp = m, np = n, pkp = pk, skp = sk;
return crypto_box(cp, mp, (long) m.Length, np, pkp, skp);
}
public static int crypto_box_open(byte[] m, byte[] c, byte[] n, byte[] pk, byte[] sk)
{
byte[] cp = c, mp = m, np = n, pkp = pk, skp = sk;
return crypto_box_open(mp, cp, (long) c.Length, np, pkp, skp);
}
}
} | 36.313953 | 104 | 0.560359 | [
"Apache-2.0"
] | Dekryptor/UCS | Ultrapowa Clash Server/Utilities/TweetNaCl/curve25519xsalsa20poly1305.cs | 3,125 | C# |
namespace Snarkorel.lkcar_schedule.json
{
public class SeasonDto
{
public string id { get; set; } //season id
public string text { get; set; }
}
}
| 19.555556 | 50 | 0.602273 | [
"MIT"
] | Snarkorel/lkcar_schedule | lkcar_schedule/json/SeasonDto.cs | 178 | C# |
namespace Ocelot.LoadBalancer.LoadBalancers
{
using Ocelot.Middleware;
using Ocelot.Responses;
using Ocelot.Values;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class RoundRobin : ILoadBalancer
{
private readonly Func<Task<List<Service>>> _services;
private readonly object _lock = new object();
private int _last;
public RoundRobin(Func<Task<List<Service>>> services)
{
_services = services;
}
public async Task<Response<ServiceHostAndPort>> Lease(DownstreamContext downstreamContext)
{
var services = await _services();
lock (_lock)
{
if (_last >= services.Count)
{
_last = 0;
}
var next = services[_last];
_last++;
return new OkResponse<ServiceHostAndPort>(next.HostAndPort);
}
}
public void Release(ServiceHostAndPort hostAndPort)
{
}
}
}
| 25.534884 | 98 | 0.558288 | [
"MIT"
] | AnthonySteele/Ocelot | src/Ocelot/LoadBalancer/LoadBalancers/RoundRobin.cs | 1,100 | C# |
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PokemonUnity;
using PokemonUnity.Monster;
using PokemonUnity.Monster.Data;
using PokemonUnity.Attack;
using PokemonUnity.Inventory;
namespace Tests
{
[TestClass]
public class PokemonTest
{
//Create 2 assert test; 1 for regular pokemon, and one for pokemon.NONE
//Pokemon.NONE cannot receive any changes to data, as it does not exist...
#region HP/Status...
[TestMethod]
public void Pokemon_SetHP_To_Zero()
{
Pokemon pokemon = new Pokemon();
pokemon.HP = 0;
Assert.AreEqual(0, pokemon.HP);
}
[TestMethod]//[ExpectedException(typeof(Exception))]
public void Pokemon_SetHP_GreaterThan_MaxHP_Equals_MaxHP()
{
Pokemon pokemon = new Pokemon();
pokemon.HP = pokemon.TotalHP + 1;
/*try
{
pokemon.HP = pokemon.TotalHP + 1;
Assert.Fail();
}
catch (Exception e)
{
//Assert.AreEqual(error, pokemon.HP);
Assert.IsTrue(e is Exception);
}*/
Assert.AreEqual(pokemon.TotalHP, pokemon.HP);
}
[TestMethod]
public void Pokemon_SetStatus_To_Burn()
{
Pokemon pokemon = new Pokemon();
pokemon.Status = Status.BURN;
Assert.AreEqual(Status.BURN, pokemon.Status);
//Assert.Inconclusive();
}
//[TestMethod]
//public void Pokemon_Sleep_StatusTurn_Not_Zero() {
// Pokemon pokemon = new Pokemon();
// pokemon.Status = Status.SLEEP;
// //If remaining turns for sleep is 0 then the pokemon would be awake.
// //I think this test only works properly if done thru battle class
// Assert.AreNotEqual(0, pokemon.StatusCount);
//}
[TestMethod]
public void Pokemon_FullyHeal()
{
Pokemon pokemon = new Pokemon();
pokemon.HP = 0;
pokemon.HealHP();
Assert.AreEqual(pokemon.TotalHP, pokemon.HP);
}
[TestMethod]
public void Pokemon_MakeFainted()
{
Pokemon pokemon = new Pokemon();
pokemon.HP = 0;
Assert.IsTrue(pokemon.isFainted());
}
[TestMethod]
public void Pokemon_SetPokerus_To_Infected()
{
Pokemon pokemon = new Pokemon();
pokemon.GivePokerus();
Assert.IsTrue(pokemon.PokerusStage.Value);
}
#endregion
#region Level/stats...
[TestMethod]
public void Pokemon_Starting_Level_NotNegative()
{
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR);
Assert.IsTrue(pokemon.Level >= 0);
}
[TestMethod]
public void Pokemon_IsEgg_At_Default_Level()
{
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR);
Assert.IsTrue(pokemon.isEgg);
}
[TestMethod]
public void Pokemon_HatchEgg()
{
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR);
pokemon.HatchEgg();
Assert.IsFalse(pokemon.isEgg);
}
[TestMethod]
public void Pokemon_Spawn_Wild_Not_Egg()
{
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR, isEgg: false);
Assert.IsFalse(pokemon.isEgg);
}
[TestMethod]
//Setting the pokemon levels controls the experience points
public void Pokemon_Set_ExperiencePoints_To_Match_Level()
{
//Assert.Inconclusive("Missing pokemon method to assign level by integer value");
byte lv = 7;
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR);
//pokemon.Level = lv;
pokemon.SetLevel(lv);
//Assert.AreEqual(lv,Experience.GetLevelFromExperience(pokemon.GrowthRate, pokemon.Exp));
Assert.AreEqual(lv,pokemon.Level);
}
[TestMethod]
// Setting the pokemon experience points controls the level
public void Pokemon_Set_Level_To_Match_ExperiencePoints()
{
byte lv = 7;
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR, level: 3);
pokemon.Exp = Experience.GetStartExperience(pokemon.GrowthRate, lv);
Assert.AreEqual(lv, pokemon.Level);
}
[TestMethod]
// Modifying pokemon experience points changes the level
public void Pokemon_Level_Changes_To_Match_ExperiencePoints()
{
byte lv = 7;
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR, level: 3);
//pokemon.Experience.AddExperience(Experience.GetStartExperience(pokemon.GrowthRate, 300));
pokemon.Experience.AddExperience(300);
//pokemon.Experience.AddExperience(Experience.GetStartExperience(pokemon.GrowthRate, lv) - pokemon.Experience.Total);
int exp = Experience.GetStartExperience(pokemon.GrowthRate, lv) - pokemon.Experience.Total;
pokemon.Experience.AddExperience(exp);
Assert.AreEqual(lv, pokemon.Level); //Experience.GetLevelFromExperience(pokemon.GrowthRate, pokemon.Experience.Total)
}
[TestMethod]
public void Pokemon_Spawn_At_Set_Level()
{
byte lv = 5;
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR, level: lv);
Assert.AreEqual(lv, Experience.GetLevelFromExperience(pokemon.GrowthRate, pokemon.Experience.Total));
}
//[TestMethod]
//public void test_experience()
//{
// /*def test_experience(use_update):
// pkmn, expected = voltorb_and_dict()
// for exp in 2197, 2200:
// if use_update:
// pkmn.update(exp=exp)
// else:
// pkmn.exp = exp
// assert pkmn.exp == exp
// assert pkmn.experience_rung.experience <= pkmn.exp
// assert pkmn.next_experience_rung.experience > pkmn.exp
// assert pkmn.experience_rung.level + 1 == pkmn.next_experience_rung.level
// assert (pkmn.experience_rung.growth_rate ==
// pkmn.next_experience_rung.growth_rate ==
// pkmn.species.growth_rate)
// assert pkmn.level == pkmn.experience_rung.level
// assert pkmn.exp_to_next == pkmn.next_experience_rung.experience - pkmn.exp
// rung_difference = (pkmn.next_experience_rung.experience -
// pkmn.experience_rung.experience)
// assert pkmn.progress_to_next == (
// pkmn.exp - pkmn.experience_rung.experience) / float(rung_difference)
// if exp == 2197:
// expected['level'] = 13
// else:
// expected['exp'] = exp
// expected['level'] = 13
// check_with_roundtrip(5, pkmn, expected)*/
// Assert.Inconclusive();
//}
//[TestMethod]
//public void Pokemon_TestPokemon_Set_To_Egg() //Fail set to egg after hatch?
//{
// Pokemon pokemon = new Pokemon(Pokemons.NONE);
// //If not egg
// if (!pokemon.isEgg) Assert.Fail();
// //else fail
// //Set to egg
//
// //Assert if egg
// Assert.Inconclusive();
//}
//[TestMethod]
//public void Pokemon_TestPokemon_Hatch_Egg()
//{
// //Set to egg
// Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR)
// {
// //eggSteps = 5;
// };
// //If not egg fail
// if (!pokemon.isEgg) Assert.Fail();
// //for loop until egg hatches
// //Assert if egg
// Assert.Inconclusive();
// //When egg hatches, values need to be set:
// //pkmn.eggsteps = 0
// //pkmn.hatchedMap = 0
// //pkmn.obtainMode = 0
//}
[TestMethod]
public void Pokemon_Egg_Hatches_When_Timer_Reaches_Zero()
{
Pokemon pokemon = new Pokemon(Pokemons.NONE); //Step counter for test pokemon is 1000
if (!pokemon.isEgg) Assert.Fail("new Pokemon isnt an Egg");
int i = 0;
while (pokemon.EggSteps != 0)//(pokemon.isEgg)
{
pokemon.AddSteps(); //goes down by 1
if (i > 1001) Assert.Fail("Infinite Loop; Results Undetermined");
}
Assert.AreEqual(false,pokemon.isEgg);
}
[TestMethod]
public void Pokemon_ChanceFor_HiddenAbility_If_Egg()
{
Pokemons pkmn = Pokemons.BULBASAUR;
Abilities Hidden = Game.PokemonData[pkmn].Ability[2];
if (Hidden == Abilities.NONE)
{
Assert.Fail("This pokemon does not have a hidden ability");
}
int i = 0;
Pokemon pokemon;
while (true)
{
pokemon = new Pokemon(pkmn);
//pokemon.HatchEgg();
bool HA = pokemon.Ability == Hidden;
if(HA) break; i++;
if (i > 30) Assert.Fail("Infinite Loop; Results Undetermined");
}
Assert.AreEqual(Hidden, pokemon.Ability);
}
[TestMethod]
public void Pokemon_IV_SoftCaps_At_MaxLevel()
{
Assert.Inconclusive("Not implemented yet");
//Each time a pokemon levels up, they should gain new IV points
//If Pokemon is at MaxLevel, they should no longer gain anymore IV points
//Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR, level:, moves:, ivs:);
//Assert.AreEqual(Pokemon.EVSTATLIMIT, pokemon.IV[(int)Stats.SPATK]);
}
[TestMethod]
public void Pokemon_NPC_TrainerPokemon_IV_IsRandom()
{
Assert.Inconclusive("Not implemented yet");
//Create new pokemon with same information
//check if stats is random each time
//Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR, level:, moves:, ivs:);
//Assert.AreEqual(Pokemon.EVSTATLIMIT, pokemon.IV[(int)Stats.SPATK]);
}
[TestMethod]
public void Pokemon_NPC_TrainerPokemon_IV_LessThen_MaxIV()
{
Assert.Inconclusive("Not implemented yet");
//create new pokemon with iv points capped
//assert if points assigned is equal to amount given
//Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR, level:, moves:, ivs:);
//Assert.AreEqual(Pokemon.EVSTATLIMIT, pokemon.IV[(int)Stats.SPATK]);
}
//Test max value for pokemon stats
[TestMethod]
public void Pokemon_EV_GreaterThan_MaxEV_Equals_MaxEV()
{
Assert.Inconclusive("Not implemented yet");
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR);
System.Collections.Generic.List<Pokemons> pkmns =
//new System.Collections.Generic.List<Pokemons>((Pokemons[])Enum.GetValues(typeof(Pokemons)));
new System.Collections.Generic.List<Pokemons>(Game.PokemonData.Keys);
int x = 3;
//Add values enough to exceed limit, check to see if capped
for (int i = 0; i < 700; i++)
{
//x = Core.Rand.Next(pkmns.Count);
//while (x == 0)// || !pkmns.Contains((Pokemons)x)
//{
// //x = Core.Rand.Next();
// //if(!pkmns.Contains((Pokemons)x))
// // x = Core.Rand.Next();
// x = Core.Rand.Next(pkmns.Count);
//}
//pokemon.GainEffort((Pokemons)x);
pokemon.GainEffort((Pokemons)pkmns[x]);
}
Assert.AreEqual(Pokemon.EVSTATLIMIT, pokemon.EV[(int)Stats.SPATK]);
}
[TestMethod]
public void Pokemon_CombinedEV_Fail_GreaterThan_EV_MaxLimit()
{
//All EV points when added together cannot be greater than a sum of MaxEVLimit
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR);
System.Collections.Generic.List<Pokemons> pkmns =
//new System.Collections.Generic.List<Pokemons>((Pokemons[])Enum.GetValues(typeof(Pokemons)));
new System.Collections.Generic.List<Pokemons>(Game.PokemonData.Keys);
int x = 0;
//Add EV till max is hit, and add together and compare total
for (int i = 0; i < 700; i++)
{
x = Core.Rand.Next(pkmns.Count);
while (x == 0)// || !pkmns.Contains((Pokemons)x)
{
//x = Core.Rand.Next();
//if(!pkmns.Contains((Pokemons)x))
// x = Core.Rand.Next();
x = Core.Rand.Next(pkmns.Count);
}
//pokemon.GainEffort((Pokemons)x);
pokemon.GainEffort((Pokemons)pkmns[x]);
}
int ev = pokemon.EV[0] + pokemon.EV[1] + pokemon.EV[2] + pokemon.EV[3] + pokemon.EV[4] + pokemon.EV[5];
//Assert.AreEqual(Pokemon.EVLIMIT, evstring.Format("EV Limit:{0}; EV Total:{1}; EV:[{2},{3},{4},{5},{6},{7}]", Pokemon.EVLIMIT, ev, pokemon.EV[0], pokemon.EV[1], pokemon.EV[2], pokemon.EV[3], pokemon.EV[4], pokemon.EV[5]));
Assert.IsTrue(Pokemon.EVLIMIT >= ev, string.Format("EV Limit:{0}; EV Total:{1}; EV:[{2},{3},{4},{5},{6},{7}]", Pokemon.EVLIMIT, ev, pokemon.EV[0], pokemon.EV[1], pokemon.EV[2], pokemon.EV[3], pokemon.EV[4], pokemon.EV[5]));
//Assert.Inconclusive("Not implemented yet");
}
#endregion
#region Moves...
[TestMethod]
public void Pokemon_DefaultMoves_NotNull()
{
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR);
Assert.IsTrue(pokemon.countMoves() > 0);
}
[TestMethod]
public void Pokemon_RNG_DefaultMoves_For_Egg()
{
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR);
if (!pokemon.isEgg) Assert.Fail("new Pokemon isnt an Egg");
Moves[] before = new Moves[] { pokemon.moves[0].MoveId, pokemon.moves[1].MoveId, pokemon.moves[2].MoveId, pokemon.moves[3].MoveId };
pokemon.GenerateMoveset();
Assert.AreNotSame(before,new Moves[] { pokemon.moves[0].MoveId, pokemon.moves[1].MoveId, pokemon.moves[2].MoveId, pokemon.moves[3].MoveId });
}
[TestMethod]
public void Pokemon_RNG_Moves_IsDifferent_For_HatchingEgg()
{
Pokemons pkmn = Pokemons.SQUIRTLE;
System.Collections.Generic.List<Moves> egg = new System.Collections.Generic.List<Moves>(); //ml.AddRange(pokemon.getMoveList(LearnMethod.egg));
System.Collections.Generic.List<Moves> lv = new System.Collections.Generic.List<Moves>(Game.PokemonMovesData[pkmn].LevelUp.Keys);
foreach (Moves item in Game.PokemonMovesData[pkmn].Egg)
{
if (!lv.Contains(item)) egg.Add(item);
}
if (egg.Count < 1) Assert.Fail("Pokemon does not any contain egg-only move");
for (int i = 0; i < 10; i++)
{
Pokemon pokemon = new Pokemon(pkmn);
if (!pokemon.isEgg) Assert.Fail("new Pokemon isnt an Egg");
//pokemon.GenerateMoveset();
//Hatch Egg Here...
pokemon.HatchEgg();
if (pokemon.isEgg) Assert.Fail("Pokemon is still an egg.");
foreach (Move move in pokemon.moves)
{
//Pass test if pokemon has moves learned from Egg-state.
if (move.MoveId != Moves.NONE
&& egg.Contains(move.MoveId)
)
{
//Assert.IsTrue if Pokemon.Move Contains exclusive egg-only moves.
Assert.IsFalse(!true, "Test is malfunctioning and refuses to mark as success");//"Pokemon contains exclusive egg only move"
Assert.IsTrue(!false, "Test is malfunctioning and refuses to mark as success");//"Pokemon contains exclusive egg only move"
Assert.AreEqual(true,!false, "Test is malfunctioning and refuses to mark as success");//"Pokemon contains exclusive egg only move"
//Assert.AreSame(true, true);//"Pokemon contains exclusive egg only move"
Assert.IsTrue(egg.Contains(move.MoveId), "Test is malfunctioning and refuses to mark as success");//"Pokemon contains exclusive egg only move"
Assert.AreEqual(true, egg.Contains(move.MoveId), "Test is malfunctioning and refuses to mark as success");//"Pokemon contains exclusive egg only move"
CollectionAssert.Contains(egg, move.MoveId, "Test is malfunctioning and refuses to mark as success");//"Pokemon contains exclusive egg only move"
Assert.Inconclusive("Test is malfunctioning and refuses to mark as success");
}
}
}
Assert.Fail("Pokemon does not contain egg-only move");
}
[TestMethod]
public void Pokemon_Reseting_Moves_IsNotEqual()
{
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR);
Moves[] before = new Moves[] { pokemon.moves[0].MoveId, pokemon.moves[1].MoveId, pokemon.moves[2].MoveId, pokemon.moves[3].MoveId };
pokemon.resetMoves();
Assert.AreNotSame(before,new Moves[] { pokemon.moves[0].MoveId, pokemon.moves[1].MoveId, pokemon.moves[2].MoveId, pokemon.moves[3].MoveId });
}
/// <summary>
/// </summary>
/// ToDo: Resetting pokemon moves should randomly shuffle between all available that pokemon can possibly learn for their level
[TestMethod]
public void Pokemon_RNG_Moves_NotEqual_PreviousMoves()
{
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR);
Moves[] before = new Moves[] { pokemon.moves[0].MoveId, pokemon.moves[1].MoveId, pokemon.moves[2].MoveId, pokemon.moves[3].MoveId };
pokemon.GenerateMoveset();
//CollectionAssert.AreNotEqual(before, new Moves[] { pokemon.moves[0].MoveId, pokemon.moves[1].MoveId, pokemon.moves[2].MoveId, pokemon.moves[3].MoveId });
CollectionAssert.AreNotEquivalent(before, new Moves[] { pokemon.moves[0].MoveId, pokemon.moves[1].MoveId, pokemon.moves[2].MoveId, pokemon.moves[3].MoveId });
}
[TestMethod]
public void Pokemon_Moves_Should_Not_Contain_Duplicates()
{
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR);
for (int i = 0; i < 30; i++)
{
if (pokemon.moves[0].MoveId != Moves.NONE &&
(
(pokemon.moves[0].MoveId == pokemon.moves[1].MoveId) ||
(pokemon.moves[0].MoveId == pokemon.moves[2].MoveId) ||
(pokemon.moves[0].MoveId == pokemon.moves[3].MoveId)
)
)
Assert.Fail();
if (pokemon.moves[1].MoveId != Moves.NONE &&
(
(pokemon.moves[1].MoveId == pokemon.moves[2].MoveId) ||
(pokemon.moves[1].MoveId == pokemon.moves[3].MoveId)
)
)
Assert.Fail();
if (pokemon.moves[2].MoveId != Moves.NONE &&
(
(pokemon.moves[2].MoveId == pokemon.moves[3].MoveId)
)
)
Assert.Fail();
//Moves[] before = new Moves[] { pokemon.moves[0].MoveId, pokemon.moves[1].MoveId, pokemon.moves[2].MoveId, pokemon.moves[3].MoveId };
pokemon.GenerateMoveset();
}
Assert.IsTrue(true);
}
[TestMethod]
public void Pokemon_TeachMove_Add_NewMove()
{
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR);
int i = 0;
while (pokemon.countMoves() == 4)
{
pokemon.GenerateMoveset();
i++;
if (i > 5) Assert.Fail("Infinite Loop; Results Undetermined");
}
Moves[] before = new Moves[] { pokemon.moves[0].MoveId, pokemon.moves[1].MoveId, pokemon.moves[2].MoveId, pokemon.moves[3].MoveId };
bool success;
pokemon.LearnMove(Moves.RAZOR_LEAF, out success, true); //if success is false, fail test
if (!success) Assert.Fail("Bool returns false, which means learning skill was unsuccessful");
//CollectionAssert.AreNotEqual(before, new Moves[] { pokemon.moves[0].MoveId, pokemon.moves[1].MoveId, pokemon.moves[2].MoveId, pokemon.moves[3].MoveId });
CollectionAssert.AreNotEquivalent(before, new Moves[] { pokemon.moves[0].MoveId, pokemon.moves[1].MoveId, pokemon.moves[2].MoveId, pokemon.moves[3].MoveId });
}
[TestMethod]
/// <summary>
/// Move list should be compatible with pokemon
/// </summary>
public void Pokemon_TeachMove_Fail_NotCompatible()
{
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR);
int i = 0;
while (pokemon.countMoves() == 4)
{
pokemon.GenerateMoveset();
i++;
if (i > 25) Assert.Fail("Infinite Loop; Results Undetermined");
}
Moves[] before = new Moves[] { pokemon.moves[0].MoveId, pokemon.moves[1].MoveId, pokemon.moves[2].MoveId, pokemon.moves[3].MoveId };
bool success;
pokemon.LearnMove(Moves.OVERHEAT, out success); //if success is true, fail test
//CollectionAssert.AreEqual(before, new Moves[] { pokemon.moves[0].MoveId, pokemon.moves[1].MoveId, pokemon.moves[2].MoveId, pokemon.moves[3].MoveId });
CollectionAssert.AreEquivalent(before, new Moves[] { pokemon.moves[0].MoveId, pokemon.moves[1].MoveId, pokemon.moves[2].MoveId, pokemon.moves[3].MoveId });
}
//[TestMethod]
//public void Pokemon_PokemonTest_CantLearn_Move_NotCompatible_With_Pokemon()
//{
// //list of moves can learn at level
// Assert.Inconclusive();
//}
[TestMethod]
/// <summary>
/// Move list must not be full to add move to pokemon
/// </summary>
public void Pokemon_Full_Moveset_Fail_TeachMove()
{
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR);
int i = 0;
while (pokemon.countMoves() != 4)
{
pokemon.GenerateMoveset();
i++;
if (i > 1000) Assert.Fail("Infinite Loop; Results Undetermined");
}
Moves[] before = new Moves[] { pokemon.moves[0].MoveId, pokemon.moves[1].MoveId, pokemon.moves[2].MoveId, pokemon.moves[3].MoveId };
bool success;
pokemon.LearnMove(Moves.TACKLE, out success); //if success is true, fail test
if (success) Assert.Fail("Bool returns true, which means learning skill was successful");
//CollectionAssert.AreEqual(before, new Moves[] { pokemon.moves[0].MoveId, pokemon.moves[1].MoveId, pokemon.moves[2].MoveId, pokemon.moves[3].MoveId });
CollectionAssert.AreEquivalent(before, new Moves[] { pokemon.moves[0].MoveId, pokemon.moves[1].MoveId, pokemon.moves[2].MoveId, pokemon.moves[3].MoveId });
}
[TestMethod]
/// <summary>
/// Remove random move, packs the move list, and confirm move is missing
/// </summary>
public void Pokemon_ForgetMove_Minus_Move()
{
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR);
int i = 0;
while (pokemon.countMoves() == 4)
{
pokemon.GenerateMoveset();
i++;
if (i > 15) Assert.Fail("Infinite Loop; Results Undetermined");
}
bool success;
pokemon.LearnMove(Moves.TACKLE, out success);
int before = pokemon.countMoves();
pokemon.DeleteMove(Moves.TACKLE);
Assert.IsTrue(pokemon.countMoves() == before - 1);
}
//[TestMethod]
//public void Pokemon_Replace_Move_Return_Different_Moves()
//{
// Assert.Inconclusive();
//}
//[TestMethod]
//public void Pokemon_Swap_Moves_Change_OrderOf_Moves()
//{
// //Loop thru all moves, make sure they're all present
// Assert.Inconclusive();
//}
//[TestMethod]
//public void Pokemon_Return_MoveList_CanLearn_At_CurrentLevel()
//{
// //Pokemon pokemon = new Pokemon();
// //Pokemon.PokemonData.GetPokemon(Pokemons.NONE).MoveTree.LevelUp.Where(x => x.Value <= this.Level).Select(x => x.Key)
// //list of moves can learn at level
// //Assert.AreSame(new Moves[] { }, new Pokemon().getMoveList());
// Assert.IsTrue(new Pokemon(Pokemons.BULBASAUR, level: 25).getMoveList(LearnMethod.levelup).Length > 0);
//}
//[TestMethod]
//public void Pokemon_PokemonTest_CantLearn_Move_NotCompatible_With_TeachMethod()
//{
// //list of moves a pokemon can learn for a given technique
// //attempt to teach move
// //confirm moves are unchanged
// Assert.Inconclusive();
//}
#endregion
#region Evolving/evolution
/*The various triggers for a Pokémon's evolution are almost as varied as the Pokémon themselves, and some Pokémon have a unique evolution method.
* The most common of them is Evolution by leveling up at or above a certain level. Other methods include the following:
* leveling up
* leveling up when friendship has reached a high level (220 or greater), sometimes only at certain times
* leveling up while holding an item, sometimes only at certain times
* leveling up while knowing a certain move or a move of a certain type
* leveling up in a certain location
* leveling up with a certain Pokémon or Pokémon of a certain type in the party
* leveling up while upside-down
* leveling up during certain types of weather
* being traded
* being traded while holding a specific item
* being traded for a specific Pokémon
* using an evolutionary stone
Some evolutions are dependent on the Pokémon's gender. For example, only female Combee can evolve into Vespiquen—male Combee cannot evolve at all.
Similarly, all Snorunt can evolve into Glalie, but only female Snorunt can evolve into Froslass. On the other hand,
male Burmy can only evolve into Mothim, while female Burmy can only evolve into Wormadam.*/
//Use eevee to test different evolve code, as it's a perfect practice test
[TestMethod]
public void Pokemon_TestPokemon_CanEvolve_AfterLevel()
{
Assert.Inconclusive("Pokemon Evolution Temp Disabled.");
Pokemon pokemon = new Pokemon(Pokemons.BULBASAUR);
if (!pokemon.hasEvolveMethod(EvolutionMethod.Level))
Assert.Fail("Unable to test if pokemon can evolve, as it does not have an evolution through leveling-up");
//Add exp
pokemon.Experience.AddExperience(105000);
if (pokemon.CanEvolveAfter(EvolutionMethod.Level, pokemon.Level).Length > 0)
Assert.Fail("Test cannot be concluded, as results will remain unchanged.");
pokemon.Experience.AddExperience(25000);
if (pokemon.CanEvolveAfter(EvolutionMethod.Level, pokemon.Level).Length == 0)
Assert.Fail("Test failed; pokemon cannot evolve due to level too tow. Lv: {0}",pokemon.Level);
//Assert is true
Assert.AreEqual(Pokemons.IVYSAUR, pokemon.CanEvolveAfter(EvolutionMethod.Level, pokemon.Level)[0]);
}
[TestMethod]
public void Pokemon_TestPokemon_EvolvePokemonUsingItems()
{
Assert.Inconclusive("Pokemon Evolution Temp Disabled.");
Items evolveStone = Items.SUN_STONE;
Pokemon pokemon = new Pokemon(Pokemons.GLOOM);
if (!pokemon.hasEvolveMethod(EvolutionMethod.Item))
Assert.Fail("Unable to test if pokemon can evolve, as it does not have an evolution through using an Item", pokemon.GetEvolutionMethods().ToString());
//Check if Pokemon condition method for evolution has been met
if (pokemon.CanEvolveAfter(EvolutionMethod.Item, evolveStone).Length == 0)
Assert.Fail("Test failed; pokemon cannot evolve due to level too tow. Lv: {0}",pokemon.Level);
//pokemon.EvolveConditionsMet(EvolutionMethod);
//Use item on Pokemon (Evolve Pokemon)
//pokemon.UseItem(evolveStone);
Assert.AreEqual(Pokemons.BELLOSSOM, pokemon.Species);
}
#endregion
#region Shadow/Heart Guage
/* The Trainer of a Shadow Pokémon cannot do any of the following with it until it is purified:
* Level it up (when it is purified, it gains all the exp. accumulated as a Shadow Pokémon, which is only when its Heart Gauge is less than three bars full).
* Evolve it (evolves when gaining exp.)
* Use a Rare Candy on it.
* Change the order of its moves.
* Delete its moves.
* Give it a nickname (due to not having an OT or ID).
* Trade it.
* Participate in Battle Mode with it.
* Enter it in battles at Phenac Stadium.
* Enter it in battles at Orre Colosseum.
Shadow Pokémon are also unable to gain effort values from battling, although vitamins can still be used on them.*/
[TestMethod]
public void Pokemon_TestPokemon_Set_To_Shadow()
{
Pokemon pokemon = new Pokemon(Pokemons.NONE);
//Shadow can be done by counting hatch steps in negative values?
//Assert.IsTrue(pokemon.isShadow);
Assert.Inconclusive("Not implemented yet");
}
[TestMethod]
public void Pokemon_TestPokemon_Shadow_Fail_To_Purify_If_HeartGuage_Not_Zero()
{
Assert.Inconclusive("Not implemented yet");
Pokemon pokemon = new Pokemon(Pokemons.NONE);
if (!pokemon.isShadow) Assert.Fail("Is not Shadow, cannot purify");
//Check guage
//Attempt to purify
//Fail if goal isnt met
//Assert.IsTrue(pokemon.isShadow);
}
#endregion
#region Shiny
/*The table below summarizes the rates at which Shiny Pokémon can be found by the methods that will be detailed below.
* The Shiny Charm can directly add to the odds for most methods, with hidden Pokémon being affected uniquely.
|Gen.II |Gen.III |Gen.IV |Gen.V |Gen.VI |Gen.VII
------------------------------------------------------------------
Base rate |1/8192 |1/4096
------------------------------------------------------------------
Breeding a Shiny Pokémon | | | | | |
(if the offspring is the |1/64 |— |— |— |— |—
opposite gender) | | | | | |
------------------------------------------------------------------
Masuda method |— |— |5/8192 |6/8192 |6/4096
------------------------------------------------------------------
Poké Radar chaining | | | | | |
(single patch): ≥40 |— |— |41/8192|— |? |—
------------------------------------------------------------------
Shiny Charm |— |— |— |+2/8192|+2/4096
------------------------------------------------------------------
Friend Safari |— |— |— |— |5/4096 |—
------------------------------------------------------------------
Consecutive fishing: ≥20 |— |— |— |— |41/4096 |—
------------------------------------------------------------------
Hidden Pokémon: | | | | | |
Search Level 200 + X |— |— |— |— |0.08% + X*0.01% |—
------------------------------------------------------------------
SOS Battles: ≥31 |— |— |— |— |— |13/4096
------------------------------------------------------------------*/
#endregion
#region Gender..
//[TestMethod]
//public void Pokemon_GenderRatio_To_Gender()
//{
// //Convert GenderRatio to Male/Female Results
// //for loop, count to 100, if results is equal to or greater than threshold, fail
// Pokemons pkmn = Pokemons.BULBASAUR;
// GenderRatio genders = Pokemon.PokemonData.GetPokemon(pkmn).MaleRatio;
// int females = 0;
// //Confirm test criteria by making sure data fits
// if (genders == GenderRatio.AlwaysFemale)
// for (int i = 0; i < 100; i++)
// {
// Pokemon pokemon = new Pokemon(pkmn);
// //Assert.IsTrue(pokemon.Ability == Pokemon.PokemonData.GetPokemon(pokemon.Species).Ability[2]); i++;
// //if (i > 5) Assert.Fail("Infinite Loop; Results Undetermined");
// if (pokemon.Gender.HasValue && !pokemon.Gender.Value) females++;
// }
// else
// Assert.Fail("Testing for gender ratio of... but pokemon gender chances are {0}", genders.ToString());
// Assert.IsTrue(females > 30);
//}
[TestMethod]
public void Pokemon_GenderRatio_OneEighthFemale()
{
//Convert GenderRatio to Male/Female Results
//for loop, count to 100, if results is equal to or greater than threshold, fail
Pokemons pkmn = Pokemons.BULBASAUR;
GenderRatio genders = Game.PokemonData[pkmn].GenderEnum;
int females = 0;
//Confirm test criteria by making sure data fits
if (genders == GenderRatio.FemaleOneEighth || !Game.PokemonData[pkmn].IsSingleGendered)
{
for (int i = 0; i < 100; i++)
{
Pokemon pokemon = new Pokemon(pkmn);
if (pokemon.Gender.HasValue && !pokemon.Gender.Value) females++;
}
Assert.IsTrue(100 - females > 100 - 18); //12.5 is 1/8th
}
else
Assert.Fail("Testing for gender ratio of {0}; but pokemon gender chances are {1}", "One-Eighth Percent Females", genders.ToString());
}
#endregion
#region Forms
/*
* Unowns and their different letters, should reference same pokemon id (same with pikachu)
* Learn moves based on form... (Deoxys)
* From change based on items...
* Form change based on gender
* Evolutions.. (some evolve into form based on specific criteria)
* Some forms are fusions...
* Some forms are purely cosmetic and change based on frontend/ui
* Some forms are battle only forms, and battle mechanic is going to be frontend only
* Pokemon Vivillion form is based on player's physical GPS location (pc IP Address)
*/
/// <see cref="Pokemons.UNOWN"/> = letter of the alphabet.
/// <see cref="Pokemons.DEOXYS"/> = which of the four forms.
/// <see cref="Pokemons.BURMY"/>/<see cref="Pokemons.WORMADAM"/> = cloak type. Does not change for Wormadam.
/// <see cref="Pokemons.SHELLOS"/>/<see cref="Pokemons.GASTRODON"/> = west/east alt colours.
/// <see cref="Pokemons.ROTOM"/> = different possesed appliance forms.
/// <see cref="Pokemons.GIRATINA"/> = Origin/Altered form.
/// <see cref="Pokemons.SHAYMIN"/> = Land/Sky form.
/// <see cref="Pokemons.ARCEUS"/> = Type.
/// <see cref="Pokemons.BASCULIN"/> = appearance.
/// <see cref="Pokemons.DEERLING"/>/<see cref="Pokemons.SAWSBUCK"/> = appearance.
/// <see cref="Pokemons.TORNADUS"/>/<see cref="Pokemons.THUNDURUS"/>/<see cref="Pokemons.LANDORUS"/> = Incarnate/Therian forms.
/// <see cref="Pokemons.KYUREM"/> = Normal/White/Black forms.
/// <see cref="Pokemons.KELDEO"/> = Ordinary/Resolute forms.
/// <see cref="Pokemons.MELOETTA"/> = Aria/Pirouette forms.
/// <see cref="Pokemons.GENESECT"/> = different Drives.
/// <see cref="Pokemons.VIVILLON"/> = different Patterns.
/// <see cref="Pokemons.FLABEBE"/>/<see cref="Pokemons.FLOETTE"/>/<see cref="Pokemons.FLORGES"/> = Flower colour.
/// <see cref="Pokemons.FURFROU"/> = haircut.
/// <see cref="Pokemons.PUMPKABOO"/>/<see cref="Pokemons.GOURGEIST"/> = small/average/large/super sizes.
/// <see cref="Pokemons.HOOPA"/> = Confined/Unbound forms.
/// <see cref="Pokemons.CASTFORM"/>? = different weather forms
/// <see cref="Pokemons.PIKACHU"/>
//Test game doesnt crash if no form
//Test pokedex to record/show (only) first form seen
//Test pokedex to record/show (different?) form captured
//Test pokemon has mega form
//Moves learned changes with form
[TestMethod]
public void Pokemon_Form_SetForm_To_FormB()
{
Pokemon pokemon = new Pokemon(Pokemons.UNOWN);
//pokemon.FormId = 1;
pokemon.SetForm(Forms.UNOWN_B);
CollectionAssert //Assert
.AreEqual( //.AreEqual(
new object[] { Pokemons.UNOWN, Forms.UNOWN_B },
//new object[] { pokemon.Species, Game.PokemonFormsData[pokemon.Species][pokemon.FormId].Id },
//string.Format("Form: {0}, Id: {1}", pokemon.FormId, Game.PokemonFormsData[pokemon.Species][pokemon.FormId].Id)
new object[] { pokemon.Species, pokemon.Form.Id },
string.Format("Form: {0}, Id: {1}", pokemon.FormId, pokemon.Form.Id)
);
//Assert.Inconclusive("Not implemented yet");
}
[TestMethod]
public void Pokemon_Form_SetForm_Fails_On_NoForms()
{
Pokemon pokemon = new Pokemon(Pokemons.DEOXYS); //Normal
//pokemon.FormId = 2; //Defense
pokemon.SetForm(Forms.DEOXYS_DEFENSE); //Defense
//pokemon.FormId = 5; //Not Indexed
pokemon.SetForm(5); //Not Indexed
//Assert.AreEqual(Forms.DEOXYS_DEFENSE, Game.PokemonFormsData[pokemon.Species][pokemon.FormId].Id);
Assert.AreEqual(Forms.DEOXYS_DEFENSE, pokemon.Form.Id);
//Assert.AreEqual(2, Game.PokemonFormsData[pokemon.Species][pokemon.Form].GetArrayId());
//Assert.Inconclusive("Not implemented yet");
}
[TestMethod]
//Changing form changes base stats
public void Pokemon_Form_SetForm_ChangesStats()
{
Pokemon pokemon = new Pokemon(Pokemons.ROTOM);
//pokemon.AddExperience(100000, false);
pokemon.Exp = 100000;
//if (Game.PokemonData[pokemon.Species].BaseStatsATK != pokemon.ATK) Assert.Fail("Bad Test; Attack not equal to Base Stats");
if(pokemon.Form.Id == Forms.ROTOM_HEAT) Assert.Fail("Bad Test; Form is already set.");
int[] stat = new int[] { pokemon.HP, pokemon.ATK, pokemon.DEF, pokemon.SPA, pokemon.SPD, pokemon.SPE };
//int[] stat = new int[] { pokemon.BaseStatsHP, pokemon.BaseStatsATK, pokemon.BaseStatsDEF, pokemon.BaseStatsSPA, pokemon.BaseStatsSPD, pokemon.BaseStatsSPE };
//pokemon.FormId = 1; //Rotom_Heat
pokemon.SetForm(Forms.ROTOM_HEAT);
//if(Game.PokemonFormsData[pokemon.Species][pokemon.FormId].Id != Forms.ROTOM_HEAT) Assert.Fail("Bad Test; Wrong Stats being modified.");
if(pokemon.Form.Id != Forms.ROTOM_HEAT) Assert.Fail("Bad Test; Wrong Stats being modified.");
//Assert.AreNotEqual(Game.PokemonData[pokemon.Species].BaseStatsATK, pokemon.ATK);
//Assert.AreNotEqual(pokemon.ATK, stat, "No changes in Pokemon stats.");
CollectionAssert.AreNotEqual(stat, new int[] { pokemon.HP, pokemon.ATK, pokemon.DEF, pokemon.SPA, pokemon.SPD, pokemon.SPE }, "No changes in Pokemon stats.");
//CollectionAssert.AreNotEquivalent(stat, new int[] { pokemon.BaseStatsHP, pokemon.BaseStatsATK, pokemon.BaseStatsDEF, pokemon.BaseStatsSPA, pokemon.BaseStatsSPD, pokemon.BaseStatsSPE }, "No changes in Pokemon stats.");
//Assert.Fail("Need to find way to compare Pokemon.baseStats to Form.baseStats");
//Assert.Inconclusive("Not implemented yet");
}
[TestMethod]
public void Pokemon_TestPokemon_GetPokemon_From_Form()
{
Pokemon pokemon = new Pokemon(Pokemons.DEOXYS_DEFENSE); //Normal
//pokemon.SetForm(2); //Pokemons don't start out in alternate forms, must call manually.
//Assert.AreEqual(Pokemons.DEOXYS, Form.GetSpecies(Forms.DEOXYS_DEFENSE));//Game.PokemonFormsData[pokemon.Species][pokemon.FormId]
//if (Pokemons.DEOXYS_DEFENSE != Form.GetSpecies(pokemon.Form.Id))//Forms.DEOXYS_DEFENSE
//if (Pokemons.DEOXYS_DEFENSE != pokemon.Form.Base)//Forms.DEOXYS_DEFENSE
if (Forms.DEOXYS_DEFENSE != pokemon.Form.Id)
Assert.Fail("Pokemon Id and FormId are not the same. Expected: <{0}> | Actual: <{1}>", Pokemons.DEOXYS_DEFENSE, pokemon.Form.Base); //Form.GetSpecies(pokemon.Form)
//This test fails...
//Assert.AreEqual(Pokemons.DEOXYS, pokemon.Species, "Pokemon Form and Breed are not the same.");
//But this test passes... should the results be flipped?
Assert.AreEqual(Pokemons.DEOXYS, pokemon.Form.Base, "Pokemon Form and Breed are not the same.");
}
#endregion
#region Misc
[TestMethod]
public void Pokemon_WildPokemon_With_Item()
{
Pokemon pkmn = new Pokemon(Pokemons.RATICATE);//Pokemons.BUTTERFREE
if (Game.PokemonItemsData[pkmn.Species].Length == 0)
Assert.Fail("Pokemon does not contain any held items in wild");
//Instantiate wild pokemon, maybe 100 times
for (int i = 0; i < 100; i++)
{
//check to see if wild pokemon is created with held item
pkmn.SwapItem(PokemonWildItems.GetWildHoldItem(pkmn.Species));
//pass if held item is true
if (pkmn.Item != Items.NONE)
//Assert.AreNotEqual()
//Assert.IsTrue(true, "test isnt passing, and i dont know why");
Assert.AreNotEqual(Items.NONE, pkmn.Item, "test isnt passing, and i dont know why");
//Maybe this one isnt needed?...
//Wild pokemons are (any/instantiated) pkmns without trainers?
}
//Assert.Inconclusive();
//Assert.Fail("Pokemon did not receive a held item");
Assert.AreNotEqual(Items.NONE, pkmn.Item, "Pokemon did not receive a held item");
}
[TestMethod]
public void Pokemon_TestPokemon_Set_Ribbons_Tier3_OutOf_4()
{
Assert.Inconclusive("Should research more on ribbon mechanic");
Pokemon pokemon = new Pokemon(Pokemons.NONE);
//Set ribbons to tier 3
//Check if contains other tiers rank 1 and 2
Assert.IsTrue(pokemon.Ribbons.Contains(Ribbon.HOENNTOUGHHYPER));
//Create 2nd assert for regular pokemon
//Assert.Fail("Pokemon NONE cannot obtain ribbons");
Assert.Inconclusive("Not implemented yet");
}
[TestMethod]
public void Pokemon_TestPokemon_Add_Ribbons_OfSameType_Increases_RankTier()
{
//Can only get the next ribbon if previous one has been acquired
Assert.Inconclusive("Should research more on ribbon mechanic");
Pokemon pokemon = new Pokemon(Pokemons.NONE);
//Add Ribbon.HOENNTOUGH x4
Assert.IsTrue(pokemon.Ribbons.Contains(Ribbon.HOENNTOUGHHYPER));
//Create 2nd assert for regular pokemon
//Assert.Fail("Pokemon NONE cannot obtain ribbons");
Assert.Inconclusive("Not implemented yet");
}
[TestMethod]
public void Pokemon_TestPokemon_Set_Markings()
{
Pokemon pokemon = new Pokemon(Pokemons.NONE)
{
Markings = new bool[] { false, true, true, false, false, false }
};
//bool[] marks = new bool[6]; marks[1] = marks[2] = true;
Assert.IsTrue(pokemon.Markings[2]);
}
[TestMethod]
public void Pokemon_Mail_Test_Pokemon_HoldMessage()
{
Pokemon pokemon = new Pokemon(Pokemons.NONE);
//Write message, Pick Mail design
//Save to pokemon
//Check pokemon and confirm it's still there
//Assert.IsNotNull(pokemon.Mail);
Assert.Inconclusive("Not implemented yet");
}
#endregion
}
} | 41.895311 | 226 | 0.682024 | [
"BSD-3-Clause"
] | AceOfSpadesProduc100/Trying-out-Pokemon-Unity | UnitTestProject/PokemonTest.cs | 38,511 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\wincodec.h(8542,5)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[ComImport, Guid("3d4c0c61-18a4-41e4-bd80-481a4fc9f464"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public partial interface IWICDdsFrameDecode
{
[PreserveSig]
HRESULT GetSizeInBlocks(/* [out] __RPC__out */ out uint pWidthInBlocks, /* [out] __RPC__out */ out uint pHeightInBlocks);
[PreserveSig]
HRESULT GetFormatInfo(/* [out] __RPC__out */ out WICDdsFormatInfo pFormatInfo);
[PreserveSig]
HRESULT CopyBlocks(/* optional(WICRect) */ IntPtr prcBoundsInBlocks, /* [in] */ uint cbStride, /* [in] */ int cbBufferSize, /* [size_is][out] __RPC__out_ecount_full(cbBufferSize) */ [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pbBuffer);
}
}
| 46.25 | 268 | 0.681081 | [
"MIT"
] | Steph55/DirectN | DirectN/DirectN/Generated/IWICDdsFrameDecode.cs | 927 | C# |
using System;
using System.Collections.ObjectModel;
using Xamarin.Forms;
namespace FormsCommunityToolkit.Effects
{
public static class SearchBarSuggestionEffect
{
public static readonly BindableProperty SuggestionsProperty = BindableProperty.CreateAttached("Suggestions", typeof(ObservableCollection<string>), typeof(SearchBarSuggestionEffect), new ObservableCollection<string>(), propertyChanged: OnSuggestionsChanged);
public static readonly BindableProperty TextChangedActionProperty = BindableProperty.CreateAttached("TextChangedAction", typeof(Action), typeof(SearchBarSuggestionEffect), null, propertyChanged: OnTextChangedActionChanged);
public static ObservableCollection<string> GetSuggestions(BindableObject view)
{
return (ObservableCollection<string>)view.GetValue(SuggestionsProperty);
}
public static void SetSuggestions(BindableObject view, ObservableCollection<string> value)
{
view.SetValue(SuggestionsProperty, value);
}
public static Action GetTextChangedAction(BindableObject view)
{
return (Action)view.GetValue(TextChangedActionProperty);
}
public static void SetTextChangedAction(BindableObject view, Action value)
{
view.SetValue(TextChangedActionProperty, value);
}
private static void OnSuggestionsChanged(BindableObject bindable, object oldValue, object newValue)
{
var view = bindable as SearchBar;
if (view == null)
return;
bindable.SetValue(SuggestionsProperty, (ObservableCollection<string>)newValue);
}
private static void OnTextChangedActionChanged(BindableObject bindable, object oldValue, object newValue)
{
var view = bindable as SearchBar;
if (view == null)
return;
bindable.SetValue(TextChangedActionProperty, (Action)newValue);
}
}
public class UWPSearchBarSuggestionEffect : RoutingEffect
{
public UWPSearchBarSuggestionEffect() : base("FormsCommunityToolkit.Effects.UWPSearchBarSuggestionEffect")
{
}
}
}
| 39.017544 | 265 | 0.698291 | [
"MIT"
] | JanDeDobbeleer/Effects | src/Effects/SearchBarSuggestionEffect.cs | 2,226 | C# |
using System;
using System.Windows.Forms;
namespace iSpyApplication
{
public partial class Prompt : Form
{
public string Val;
public Prompt()
{
InitializeComponent();
button1.Text = LocRm.GetString("OK");
}
public Prompt(string label, string prefill="", bool isPassword=false)
{
InitializeComponent();
Text = label;
textBox1.Text = prefill;
if (isPassword)
textBox1.PasswordChar = '*';
}
public override sealed string Text
{
get { return base.Text; }
set { base.Text = value; }
}
private void button1_Click(object sender, EventArgs e)
{
Go();
}
private void Go()
{
DialogResult = DialogResult.OK;
Val = textBox1.Text;
Close();
}
private void Prompt_Load(object sender, EventArgs e)
{
}
private void Prompt_Shown(object sender, EventArgs e)
{
this.Activate();
textBox1.Focus();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Go();
}
}
}
}
| 22.03125 | 78 | 0.460993 | [
"Apache-2.0"
] | isaacandy/ispyconnect | iSpyApplication/Prompt.cs | 1,412 | C# |
// DeflateStream.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009-2010 Dino Chiesa.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2011-July-31 14:48:11>
//
// ------------------------------------------------------------------
//
// This module defines the DeflateStream class, which can be used as a replacement for
// the System.IO.Compression.DeflateStream class in the .NET BCL.
//
// ------------------------------------------------------------------
using System;
namespace MonoGame.Utilities.Deflate
{
/// <summary>
/// A class for compressing and decompressing streams using the Deflate algorithm.
/// </summary>
///
/// <remarks>
///
/// <para>
/// The DeflateStream is a <see
/// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a <see
/// cref="System.IO.Stream"/>. It adds DEFLATE compression or decompression to any
/// stream.
/// </para>
///
/// <para>
/// Using this stream, applications can compress or decompress data via stream
/// <c>Read</c> and <c>Write</c> operations. Either compresssion or decompression
/// can occur through either reading or writing. The compression format used is
/// DEFLATE, which is documented in <see
/// href="http://www.ietf.org/rfc/rfc1951.txt">IETF RFC 1951</see>, "DEFLATE
/// Compressed Data Format Specification version 1.3.".
/// </para>
///
/// <para>
/// This class is similar to <see cref="ZlibStream"/>, except that
/// <c>ZlibStream</c> adds the <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC
/// 1950 - ZLIB</see> framing bytes to a compressed stream when compressing, or
/// expects the RFC1950 framing bytes when decompressing. The <c>DeflateStream</c>
/// does not.
/// </para>
///
/// </remarks>
///
/// <seealso cref="ZlibStream" />
/// <seealso cref="GZipStream" />
public class DeflateStream : System.IO.Stream
{
internal ZlibBaseStream _baseStream;
internal System.IO.Stream _innerStream;
bool _disposed;
/// <summary>
/// Create a DeflateStream using the specified CompressionMode.
/// </summary>
///
/// <remarks>
/// When mode is <c>CompressionMode.Compress</c>, the DeflateStream will use
/// the default compression level. The "captive" stream will be closed when
/// the DeflateStream is closed.
/// </remarks>
///
/// <example>
/// This example uses a DeflateStream to compress data from a file, and writes
/// the compressed data to another file.
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(fileToCompress + ".deflated"))
/// {
/// using (Stream compressor = new DeflateStream(raw, CompressionMode.Compress))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n;
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
///
/// <code lang="VB">
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(fileToCompress & ".deflated")
/// Using compressor As Stream = New DeflateStream(raw, CompressionMode.Compress)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
/// <param name="stream">The stream which will be read or written.</param>
/// <param name="mode">Indicates whether the DeflateStream will compress or decompress.</param>
public DeflateStream(System.IO.Stream stream, CompressionMode mode)
: this(stream, mode, CompressionLevel.Default, false)
{
}
/// <summary>
/// Create a DeflateStream using the specified CompressionMode and the specified CompressionLevel.
/// </summary>
///
/// <remarks>
///
/// <para>
/// When mode is <c>CompressionMode.Decompress</c>, the level parameter is
/// ignored. The "captive" stream will be closed when the DeflateStream is
/// closed.
/// </para>
///
/// </remarks>
///
/// <example>
///
/// This example uses a DeflateStream to compress data from a file, and writes
/// the compressed data to another file.
///
/// <code>
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(fileToCompress + ".deflated"))
/// {
/// using (Stream compressor = new DeflateStream(raw,
/// CompressionMode.Compress,
/// CompressionLevel.BestCompression))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n= -1;
/// while (n != 0)
/// {
/// if (n > 0)
/// compressor.Write(buffer, 0, n);
/// n= input.Read(buffer, 0, buffer.Length);
/// }
/// }
/// }
/// }
/// </code>
///
/// <code lang="VB">
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(fileToCompress & ".deflated")
/// Using compressor As Stream = New DeflateStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
/// <param name="stream">The stream to be read or written while deflating or inflating.</param>
/// <param name="mode">Indicates whether the <c>DeflateStream</c> will compress or decompress.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
public DeflateStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level)
: this(stream, mode, level, false)
{
}
/// <summary>
/// Create a <c>DeflateStream</c> using the specified
/// <c>CompressionMode</c>, and explicitly specify whether the
/// stream should be left open after Deflation or Inflation.
/// </summary>
///
/// <remarks>
///
/// <para>
/// This constructor allows the application to request that the captive stream
/// remain open after the deflation or inflation occurs. By default, after
/// <c>Close()</c> is called on the stream, the captive stream is also
/// closed. In some cases this is not desired, for example if the stream is a
/// memory stream that will be re-read after compression. Specify true for
/// the <paramref name="leaveOpen"/> parameter to leave the stream open.
/// </para>
///
/// <para>
/// The <c>DeflateStream</c> will use the default compression level.
/// </para>
///
/// <para>
/// See the other overloads of this constructor for example code.
/// </para>
/// </remarks>
///
/// <param name="stream">
/// The stream which will be read or written. This is called the
/// "captive" stream in other places in this documentation.
/// </param>
///
/// <param name="mode">
/// Indicates whether the <c>DeflateStream</c> will compress or decompress.
/// </param>
///
/// <param name="leaveOpen">true if the application would like the stream to
/// remain open after inflation/deflation.</param>
public DeflateStream(System.IO.Stream stream, CompressionMode mode, bool leaveOpen)
: this(stream, mode, CompressionLevel.Default, leaveOpen)
{
}
/// <summary>
/// Create a <c>DeflateStream</c> using the specified <c>CompressionMode</c>
/// and the specified <c>CompressionLevel</c>, and explicitly specify whether
/// the stream should be left open after Deflation or Inflation.
/// </summary>
///
/// <remarks>
///
/// <para>
/// When mode is <c>CompressionMode.Decompress</c>, the level parameter is ignored.
/// </para>
///
/// <para>
/// This constructor allows the application to request that the captive stream
/// remain open after the deflation or inflation occurs. By default, after
/// <c>Close()</c> is called on the stream, the captive stream is also
/// closed. In some cases this is not desired, for example if the stream is a
/// <see cref="System.IO.MemoryStream"/> that will be re-read after
/// compression. Specify true for the <paramref name="leaveOpen"/> parameter
/// to leave the stream open.
/// </para>
///
/// </remarks>
///
/// <example>
///
/// This example shows how to use a <c>DeflateStream</c> to compress data from
/// a file, and store the compressed data into another file.
///
/// <code>
/// using (var output = System.IO.File.Create(fileToCompress + ".deflated"))
/// {
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (Stream compressor = new DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true))
/// {
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n= -1;
/// while (n != 0)
/// {
/// if (n > 0)
/// compressor.Write(buffer, 0, n);
/// n= input.Read(buffer, 0, buffer.Length);
/// }
/// }
/// }
/// // can write additional data to the output stream here
/// }
/// </code>
///
/// <code lang="VB">
/// Using output As FileStream = File.Create(fileToCompress & ".deflated")
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using compressor As Stream = New DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True)
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// ' can write additional data to the output stream here.
/// End Using
/// </code>
/// </example>
/// <param name="stream">The stream which will be read or written.</param>
/// <param name="mode">Indicates whether the DeflateStream will compress or decompress.</param>
/// <param name="leaveOpen">true if the application would like the stream to remain open after inflation/deflation.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
public DeflateStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen)
{
_innerStream = stream;
_baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.DEFLATE, leaveOpen);
}
#region Zlib properties
/// <summary>
/// This property sets the flush behavior on the stream.
/// </summary>
/// <remarks> See the ZLIB documentation for the meaning of the flush behavior.
/// </remarks>
virtual public FlushType FlushMode
{
get { return (this._baseStream._flushMode); }
set
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
this._baseStream._flushMode = value;
}
}
/// <summary>
/// The size of the working buffer for the compression codec.
/// </summary>
///
/// <remarks>
/// <para>
/// The working buffer is used for all stream operations. The default size is
/// 1024 bytes. The minimum size is 128 bytes. You may get better performance
/// with a larger buffer. Then again, you might not. You would have to test
/// it.
/// </para>
///
/// <para>
/// Set this before the first call to <c>Read()</c> or <c>Write()</c> on the
/// stream. If you try to set it afterwards, it will throw.
/// </para>
/// </remarks>
public int BufferSize
{
get
{
return this._baseStream._bufferSize;
}
set
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
if (this._baseStream._workingBuffer != null)
throw new ZlibException("The working buffer is already set.");
if (value < ZlibConstants.WorkingBufferSizeMin)
throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, ZlibConstants.WorkingBufferSizeMin));
this._baseStream._bufferSize = value;
}
}
/// <summary>
/// The ZLIB strategy to be used during compression.
/// </summary>
///
/// <remarks>
/// By tweaking this parameter, you may be able to optimize the compression for
/// data with particular characteristics.
/// </remarks>
public CompressionStrategy Strategy
{
get
{
return this._baseStream.Strategy;
}
set
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
this._baseStream.Strategy = value;
}
}
/// <summary> Returns the total number of bytes input so far.</summary>
virtual public long TotalIn
{
get
{
return this._baseStream._z.TotalBytesIn;
}
}
/// <summary> Returns the total number of bytes output so far.</summary>
virtual public long TotalOut
{
get
{
return this._baseStream._z.TotalBytesOut;
}
}
#endregion
#region System.IO.Stream methods
/// <summary>
/// Dispose the stream.
/// </summary>
/// <remarks>
/// <para>
/// This may or may not result in a <c>Close()</c> call on the captive
/// stream. See the constructors that have a <c>leaveOpen</c> parameter
/// for more information.
/// </para>
/// <para>
/// Application code won't call this code directly. This method may be
/// invoked in two distinct scenarios. If disposing == true, the method
/// has been called directly or indirectly by a user's code, for example
/// via the public Dispose() method. In this case, both managed and
/// unmanaged resources can be referenced and disposed. If disposing ==
/// false, the method has been called by the runtime from inside the
/// object finalizer and this method should not reference other objects;
/// in that case only unmanaged resources must be referenced or
/// disposed.
/// </para>
/// </remarks>
/// <param name="disposing">
/// true if the Dispose method was invoked by user code.
/// </param>
protected override void Dispose(bool disposing)
{
try
{
if (!_disposed)
{
if (disposing && (this._baseStream != null))
this._baseStream.Dispose();
_disposed = true;
}
}
finally
{
base.Dispose(disposing);
}
}
/// <summary>
/// Indicates whether the stream can be read.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports reading.
/// </remarks>
public override bool CanRead
{
get
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
return _baseStream._stream.CanRead;
}
}
/// <summary>
/// Indicates whether the stream supports Seek operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream can be written.
/// </summary>
/// <remarks>
/// The return value depends on whether the captive stream supports writing.
/// </remarks>
public override bool CanWrite
{
get
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
return _baseStream._stream.CanWrite;
}
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
_baseStream.Flush();
}
/// <summary>
/// Reading this property always throws a <see cref="NotImplementedException"/>.
/// </summary>
public override long Length
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// The position of the stream pointer.
/// </summary>
///
/// <remarks>
/// Setting this property always throws a <see
/// cref="NotImplementedException"/>. Reading will return the total bytes
/// written out, if used in writing, or the total bytes read in, if used in
/// reading. The count may refer to compressed bytes or uncompressed bytes,
/// depending on how you've used the stream.
/// </remarks>
public override long Position
{
get
{
if (this._baseStream._streamMode == MonoGame.Utilities.Deflate.ZlibBaseStream.StreamMode.Writer)
return this._baseStream._z.TotalBytesOut;
if (this._baseStream._streamMode == MonoGame.Utilities.Deflate.ZlibBaseStream.StreamMode.Reader)
return this._baseStream._z.TotalBytesIn;
return 0;
}
set { throw new NotImplementedException(); }
}
/// <summary>
/// Read data from the stream.
/// </summary>
/// <remarks>
///
/// <para>
/// If you wish to use the <c>DeflateStream</c> to compress data while
/// reading, you can create a <c>DeflateStream</c> with
/// <c>CompressionMode.Compress</c>, providing an uncompressed data stream.
/// Then call Read() on that <c>DeflateStream</c>, and the data read will be
/// compressed as you read. If you wish to use the <c>DeflateStream</c> to
/// decompress data while reading, you can create a <c>DeflateStream</c> with
/// <c>CompressionMode.Decompress</c>, providing a readable compressed data
/// stream. Then call Read() on that <c>DeflateStream</c>, and the data read
/// will be decompressed as you read.
/// </para>
///
/// <para>
/// A <c>DeflateStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not both.
/// </para>
///
/// </remarks>
/// <param name="buffer">The buffer into which the read data should be placed.</param>
/// <param name="offset">the offset within that data array to put the first byte read.</param>
/// <param name="count">the number of bytes to read.</param>
/// <returns>the number of bytes actually read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
return _baseStream.Read(buffer, offset, count);
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="offset">this is irrelevant, since it will always throw!</param>
/// <param name="origin">this is irrelevant, since it will always throw!</param>
/// <returns>irrelevant!</returns>
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotImplementedException();
}
/// <summary>
/// Calling this method always throws a <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="value">this is irrelevant, since it will always throw!</param>
public override void SetLength(long value)
{
throw new NotImplementedException();
}
/// <summary>
/// Write data to the stream.
/// </summary>
/// <remarks>
///
/// <para>
/// If you wish to use the <c>DeflateStream</c> to compress data while
/// writing, you can create a <c>DeflateStream</c> with
/// <c>CompressionMode.Compress</c>, and a writable output stream. Then call
/// <c>Write()</c> on that <c>DeflateStream</c>, providing uncompressed data
/// as input. The data sent to the output stream will be the compressed form
/// of the data written. If you wish to use the <c>DeflateStream</c> to
/// decompress data while writing, you can create a <c>DeflateStream</c> with
/// <c>CompressionMode.Decompress</c>, and a writable output stream. Then
/// call <c>Write()</c> on that stream, providing previously compressed
/// data. The data sent to the output stream will be the decompressed form of
/// the data written.
/// </para>
///
/// <para>
/// A <c>DeflateStream</c> can be used for <c>Read()</c> or <c>Write()</c>,
/// but not both.
/// </para>
///
/// </remarks>
///
/// <param name="buffer">The buffer holding data to write to the stream.</param>
/// <param name="offset">the offset within that data array to find the first byte to write.</param>
/// <param name="count">the number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (_disposed) throw new ObjectDisposedException("DeflateStream");
_baseStream.Write(buffer, offset, count);
}
#endregion
/// <summary>
/// Compress a string into a byte array using DEFLATE (RFC 1951).
/// </summary>
///
/// <remarks>
/// Uncompress it with <see cref="DeflateStream.UncompressString(byte[])"/>.
/// </remarks>
///
/// <seealso cref="DeflateStream.UncompressString(byte[])">DeflateStream.UncompressString(byte[])</seealso>
/// <seealso cref="DeflateStream.CompressBuffer(byte[])">DeflateStream.CompressBuffer(byte[])</seealso>
/// <seealso cref="GZipStream.CompressString(string)">GZipStream.CompressString(string)</seealso>
/// <seealso cref="ZlibStream.CompressString(string)">ZlibStream.CompressString(string)</seealso>
///
/// <param name="s">
/// A string to compress. The string will first be encoded
/// using UTF8, then compressed.
/// </param>
///
/// <returns>The string in compressed form</returns>
public static byte[] CompressString(String s)
{
using (var ms = new System.IO.MemoryStream())
{
System.IO.Stream compressor =
new DeflateStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression);
ZlibBaseStream.CompressString(s, compressor);
return ms.ToArray();
}
}
/// <summary>
/// Compress a byte array into a new byte array using DEFLATE.
/// </summary>
///
/// <remarks>
/// Uncompress it with <see cref="DeflateStream.UncompressBuffer(byte[])"/>.
/// </remarks>
///
/// <seealso cref="DeflateStream.CompressString(string)">DeflateStream.CompressString(string)</seealso>
/// <seealso cref="DeflateStream.UncompressBuffer(byte[])">DeflateStream.UncompressBuffer(byte[])</seealso>
/// <seealso cref="GZipStream.CompressBuffer(byte[])">GZipStream.CompressBuffer(byte[])</seealso>
/// <seealso cref="ZlibStream.CompressBuffer(byte[])">ZlibStream.CompressBuffer(byte[])</seealso>
///
/// <param name="b">
/// A buffer to compress.
/// </param>
///
/// <returns>The data in compressed form</returns>
public static byte[] CompressBuffer(byte[] b)
{
using (var ms = new System.IO.MemoryStream())
{
System.IO.Stream compressor =
new DeflateStream( ms, CompressionMode.Compress, CompressionLevel.BestCompression );
ZlibBaseStream.CompressBuffer(b, compressor);
return ms.ToArray();
}
}
/// <summary>
/// Uncompress a DEFLATE'd byte array into a single string.
/// </summary>
///
/// <seealso cref="DeflateStream.CompressString(String)">DeflateStream.CompressString(String)</seealso>
/// <seealso cref="DeflateStream.UncompressBuffer(byte[])">DeflateStream.UncompressBuffer(byte[])</seealso>
/// <seealso cref="GZipStream.UncompressString(byte[])">GZipStream.UncompressString(byte[])</seealso>
/// <seealso cref="ZlibStream.UncompressString(byte[])">ZlibStream.UncompressString(byte[])</seealso>
///
/// <param name="compressed">
/// A buffer containing DEFLATE-compressed data.
/// </param>
///
/// <returns>The uncompressed string</returns>
public static String UncompressString(byte[] compressed)
{
using (var input = new System.IO.MemoryStream(compressed))
{
System.IO.Stream decompressor =
new DeflateStream(input, CompressionMode.Decompress);
return ZlibBaseStream.UncompressString(compressed, decompressor);
}
}
/// <summary>
/// Uncompress a DEFLATE'd byte array into a byte array.
/// </summary>
///
/// <seealso cref="DeflateStream.CompressBuffer(byte[])">DeflateStream.CompressBuffer(byte[])</seealso>
/// <seealso cref="DeflateStream.UncompressString(byte[])">DeflateStream.UncompressString(byte[])</seealso>
/// <seealso cref="GZipStream.UncompressBuffer(byte[])">GZipStream.UncompressBuffer(byte[])</seealso>
/// <seealso cref="ZlibStream.UncompressBuffer(byte[])">ZlibStream.UncompressBuffer(byte[])</seealso>
///
/// <param name="compressed">
/// A buffer containing data that has been compressed with DEFLATE.
/// </param>
///
/// <returns>The data in uncompressed form</returns>
public static byte[] UncompressBuffer(byte[] compressed)
{
using (var input = new System.IO.MemoryStream(compressed))
{
System.IO.Stream decompressor =
new DeflateStream( input, CompressionMode.Decompress );
return ZlibBaseStream.UncompressBuffer(compressed, decompressor);
}
}
}
}
| 41.074224 | 168 | 0.531016 | [
"MIT"
] | 06needhamt/MonoGame | MonoGame.Framework/Utilities/Deflate/DeflateStream.cs | 30,436 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.