commit
stringlengths
40
40
subject
stringlengths
4
1.73k
repos
stringlengths
5
127k
old_file
stringlengths
2
751
new_file
stringlengths
2
751
new_contents
stringlengths
1
8.98k
old_contents
stringlengths
0
6.59k
license
stringclasses
13 values
lang
stringclasses
23 values
fce54b60a213228764b5e1b1a660306197c02820
relocate screencast to youtube
tbyehl/boxstarter,modulexcite/boxstarter,smaglio81/boxstarter,cam1985/boxstarter,dex1on/pub,dhilgarth/boxstarter,fhchina/boxstarter,modulexcite/boxstarter,mwrock/boxstarter,smaglio81/boxstarter,fhchina/boxstarter,cam1985/boxstarter,dex1on/pub,tbyehl/boxstarter,cam1985/boxstarter,dhilgarth/boxstarter,smaglio81/boxstarter,tbyehl/boxstarter,napramirez/boxstarter,fhchina/boxstarter,dex1on/pub,mwrock/boxstarter,napramirez/boxstarter,napramirez/boxstarter,dhilgarth/boxstarter,modulexcite/boxstarter
Web/index.cshtml
Web/index.cshtml
@{ Layout = "~/_SiteLayout.cshtml"; } @section featured { <div class="jumbotron"> <div class="container"> <div class="media"> <a class="pull-left" href="#"> <img height="270" class="media-object" src="images/boxlogo.png" width="270"> </a> <div class="media-body"> <h1>Boxstarter</h1> <p>Repeatable, <span class="text-primary"><b>reboot resilient</b></span> windows environment installations made easy using <a href="http://chocolatey.org">Chocolatey</a> packages. When its time to repave either <span class="text-primary"><b>bare metal or virtualized</b></span> instances, locally or on a <span class="text-primary"><b>remote machine</b></span>, Boxstarter can automate both trivial and highly complex installations. Compatible with all Windows versions from <span class="text-primary"><b>Windows 7/2008 R2 forward</b></span>.</p> <p><a class="btn btn-primary btn-lg" role="button" href="downloads/Boxstarter.@(Helper.Version()).zip"><span class="glyphicon glyphicon-cloud-download"></span> Download v@(Helper.Version())</a></p> </div> </div> </div> </div> } <div class="row"> <div class="col-md-4"> <h2><a href="WhyBoxstarter">Why Boxstarter?</a></h2> <p>Checkout the features that Boxstarter provides on top of Chocolatey to ensure 100% uninterrupted Windows environment installs.</p> <h2><a href="/InstallingPackages#RemoteInstallations">Run Remotely</a></h2> <p>Need to install a bunch of machines or repeatedly setup a VM? Invoke Boxstarter commands to install environments on remote machines.</p> </div> <div class="col-md-4"> <h2><a href="WebLauncher">Launch with one easy URL</a></h2> <p>You can use Boxstarter to install a complete environment or install a small set of tools and windows settings with absolutely no software pre installed using an easy to remember URL.</p> <h2><a href="/CreatingPackages">Simplify Package Creation</a></h2> <p>Boxstarter composes an environment using <a href="http://chocolatey.org">Chocolatey</a> style <a href="http://nuget.org">Nuget</a> Packages. Boxstarter provides commands to make package authoring a snap.</p> </div> <div class="col-md-4"> <h2>Boxstarter, The Movie</h2> <iframe width="420" height="315" src="//www.youtube.com/embed/abd4F00Mfrg" frameborder="0" allowfullscreen></iframe> </div> </div>
@{ Layout = "~/_SiteLayout.cshtml"; } @section featured { <div class="jumbotron"> <div class="container"> <div class="media"> <a class="pull-left" href="#"> <img height="270" class="media-object" src="images/boxlogo.png" width="270"> </a> <div class="media-body"> <h1>Boxstarter</h1> <p>Repeatable, <span class="text-primary"><b>reboot resilient</b></span> windows environment installations made easy using <a href="http://chocolatey.org">Chocolatey</a> packages. When its time to repave either <span class="text-primary"><b>bare metal or virtualized</b></span> instances, locally or on a <span class="text-primary"><b>remote machine</b></span>, Boxstarter can automate both trivial and highly complex installations. Compatible with all Windows versions from <span class="text-primary"><b>Windows 7/2008 R2 forward</b></span>.</p> <p><a class="btn btn-primary btn-lg" role="button" href="downloads/Boxstarter.@(Helper.Version()).zip"><span class="glyphicon glyphicon-cloud-download"></span> Download v@(Helper.Version())</a></p> </div> </div> </div> </div> } <div class="row"> <div class="col-md-4"> <h2><a href="WhyBoxstarter">Why Boxstarter?</a></h2> <p>Checkout the features that Boxstarter provides on top of Chocolatey to ensure 100% uninterrupted Windows environment installs.</p> <h2><a href="/InstallingPackages#RemoteInstallations">Run Remotely</a></h2> <p>Need to install a bunch of machines or repeatedly setup a VM? Invoke Boxstarter commands to install environments on remote machines.</p> </div> <div class="col-md-4"> <h2><a href="WebLauncher">Launch with one easy URL</a></h2> <p>You can use Boxstarter to install a complete environment or install a small set of tools and windows settings with absolutely no software pre installed using an easy to remember URL.</p> <h2><a href="/CreatingPackages">Simplify Package Creation</a></h2> <p>Boxstarter composes an environment using <a href="http://chocolatey.org">Chocolatey</a> style <a href="http://nuget.org">Nuget</a> Packages. Boxstarter provides commands to make package authoring a snap.</p> </div> <div class="col-md-4"> <h2>Boxstarter, The Movie</h2> <iframe class="tscplayer_inline embeddedObject" name="tsc_player" scrolling="no" frameborder="0" type="text/html" style="overflow:hidden;" src="http://www.screencast.com/users/mwrock/folders/Camtasia Studio/media/5a8df2cd-de47-4658-9d65-8b41a7a3f190/embed" height="300" width="380" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> </div> </div>
apache-2.0
C#
229b2bd42ed0c9836dcc3c3125bb3f58e377f54b
Update Spacefolder.cs
KerbaeAdAstra/KerbalFuture
KerbalFuture/Spacefolder.cs
KerbalFuture/Spacefolder.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using KSP; namespace SpaceFolderDrive {
mit
C#
40bb1ca270b40d395209360779fb5b161702fa90
remove failing globalization test on Linux
shrutigarg/corefx,rahku/corefx,jlin177/corefx,richlander/corefx,manu-silicon/corefx,Petermarcu/corefx,khdang/corefx,tijoytom/corefx,tstringer/corefx,mellinoe/corefx,billwert/corefx,elijah6/corefx,SGuyGe/corefx,JosephTremoulet/corefx,tstringer/corefx,shrutigarg/corefx,lggomez/corefx,janhenke/corefx,stephenmichaelf/corefx,ptoonen/corefx,adamralph/corefx,shmao/corefx,wtgodbe/corefx,vs-team/corefx,rjxby/corefx,billwert/corefx,ptoonen/corefx,n1ghtmare/corefx,tijoytom/corefx,ptoonen/corefx,dhoehna/corefx,elijah6/corefx,lggomez/corefx,yizhang82/corefx,billwert/corefx,lggomez/corefx,tstringer/corefx,dotnet-bot/corefx,shmao/corefx,dhoehna/corefx,s0ne0me/corefx,tstringer/corefx,dtrebbien/corefx,Priya91/corefx-1,jhendrixMSFT/corefx,janhenke/corefx,lggomez/corefx,krk/corefx,JosephTremoulet/corefx,parjong/corefx,ellismg/corefx,josguil/corefx,marksmeltzer/corefx,rubo/corefx,ericstj/corefx,axelheer/corefx,parjong/corefx,dtrebbien/corefx,rahku/corefx,Jiayili1/corefx,rajansingh10/corefx,ptoonen/corefx,DnlHarvey/corefx,yizhang82/corefx,shahid-pk/corefx,alphonsekurian/corefx,dhoehna/corefx,cartermp/corefx,vs-team/corefx,rahku/corefx,ViktorHofer/corefx,cartermp/corefx,shmao/corefx,twsouthwick/corefx,krk/corefx,Chrisboh/corefx,mellinoe/corefx,tstringer/corefx,kkurni/corefx,marksmeltzer/corefx,stone-li/corefx,adamralph/corefx,MaggieTsang/corefx,josguil/corefx,heXelium/corefx,richlander/corefx,jcme/corefx,the-dwyer/corefx,Petermarcu/corefx,Yanjing123/corefx,alexperovich/corefx,ravimeda/corefx,alexandrnikitin/corefx,gkhanna79/corefx,ViktorHofer/corefx,690486439/corefx,MaggieTsang/corefx,PatrickMcDonald/corefx,jcme/corefx,zhenlan/corefx,seanshpark/corefx,Yanjing123/corefx,PatrickMcDonald/corefx,fgreinacher/corefx,parjong/corefx,kkurni/corefx,manu-silicon/corefx,nbarbettini/corefx,khdang/corefx,vs-team/corefx,JosephTremoulet/corefx,rajansingh10/corefx,DnlHarvey/corefx,krk/corefx,axelheer/corefx,mellinoe/corefx,rjxby/corefx,mmitche/corefx,stormleoxia/corefx,Petermarcu/corefx,ericstj/corefx,jhendrixMSFT/corefx,pallavit/corefx,YoupHulsebos/corefx,benpye/corefx,comdiv/corefx,dsplaisted/corefx,khdang/corefx,gregg-miskelly/corefx,rubo/corefx,MaggieTsang/corefx,jeremymeng/corefx,Petermarcu/corefx,twsouthwick/corefx,alphonsekurian/corefx,Yanjing123/corefx,bitcrazed/corefx,nbarbettini/corefx,mokchhya/corefx,ViktorHofer/corefx,Ermiar/corefx,ravimeda/corefx,axelheer/corefx,rjxby/corefx,dtrebbien/corefx,weltkante/corefx,mazong1123/corefx,Priya91/corefx-1,cartermp/corefx,benjamin-bader/corefx,tstringer/corefx,twsouthwick/corefx,mellinoe/corefx,weltkante/corefx,ravimeda/corefx,alexandrnikitin/corefx,shrutigarg/corefx,mafiya69/corefx,richlander/corefx,tijoytom/corefx,jlin177/corefx,iamjasonp/corefx,rahku/corefx,heXelium/corefx,ericstj/corefx,mafiya69/corefx,nbarbettini/corefx,rahku/corefx,ravimeda/corefx,nbarbettini/corefx,shrutigarg/corefx,nchikanov/corefx,axelheer/corefx,iamjasonp/corefx,n1ghtmare/corefx,ptoonen/corefx,andyhebear/corefx,shimingsg/corefx,ericstj/corefx,ViktorHofer/corefx,billwert/corefx,ptoonen/corefx,dotnet-bot/corefx,axelheer/corefx,ptoonen/corefx,dotnet-bot/corefx,yizhang82/corefx,Ermiar/corefx,Petermarcu/corefx,seanshpark/corefx,manu-silicon/corefx,Ermiar/corefx,akivafr123/corefx,weltkante/corefx,jhendrixMSFT/corefx,SGuyGe/corefx,jlin177/corefx,bitcrazed/corefx,gkhanna79/corefx,elijah6/corefx,elijah6/corefx,mmitche/corefx,krytarowski/corefx,DnlHarvey/corefx,BrennanConroy/corefx,ellismg/corefx,shmao/corefx,khdang/corefx,Jiayili1/corefx,Chrisboh/corefx,benpye/corefx,JosephTremoulet/corefx,stone-li/corefx,twsouthwick/corefx,cydhaselton/corefx,seanshpark/corefx,Priya91/corefx-1,ellismg/corefx,ellismg/corefx,rajansingh10/corefx,n1ghtmare/corefx,jhendrixMSFT/corefx,Ermiar/corefx,Jiayili1/corefx,iamjasonp/corefx,mmitche/corefx,nchikanov/corefx,dotnet-bot/corefx,seanshpark/corefx,Chrisboh/corefx,DnlHarvey/corefx,lggomez/corefx,nchikanov/corefx,pallavit/corefx,nbarbettini/corefx,mokchhya/corefx,mmitche/corefx,mokchhya/corefx,nchikanov/corefx,vidhya-bv/corefx-sorting,shimingsg/corefx,billwert/corefx,jeremymeng/corefx,alexandrnikitin/corefx,cydhaselton/corefx,rjxby/corefx,Ermiar/corefx,benpye/corefx,lggomez/corefx,mafiya69/corefx,zhenlan/corefx,krk/corefx,YoupHulsebos/corefx,mellinoe/corefx,rubo/corefx,marksmeltzer/corefx,benjamin-bader/corefx,benjamin-bader/corefx,yizhang82/corefx,parjong/corefx,jhendrixMSFT/corefx,iamjasonp/corefx,benpye/corefx,bitcrazed/corefx,seanshpark/corefx,Alcaro/corefx,ravimeda/corefx,comdiv/corefx,pallavit/corefx,dtrebbien/corefx,vidhya-bv/corefx-sorting,ericstj/corefx,zhenlan/corefx,weltkante/corefx,cydhaselton/corefx,krytarowski/corefx,shahid-pk/corefx,shmao/corefx,YoupHulsebos/corefx,khdang/corefx,shmao/corefx,nchikanov/corefx,alexperovich/corefx,jhendrixMSFT/corefx,zhenlan/corefx,kkurni/corefx,alphonsekurian/corefx,marksmeltzer/corefx,krytarowski/corefx,shimingsg/corefx,mazong1123/corefx,Alcaro/corefx,MaggieTsang/corefx,the-dwyer/corefx,shimingsg/corefx,wtgodbe/corefx,manu-silicon/corefx,mokchhya/corefx,Priya91/corefx-1,wtgodbe/corefx,gkhanna79/corefx,josguil/corefx,mokchhya/corefx,DnlHarvey/corefx,heXelium/corefx,jcme/corefx,Priya91/corefx-1,Chrisboh/corefx,shahid-pk/corefx,shahid-pk/corefx,vidhya-bv/corefx-sorting,SGuyGe/corefx,the-dwyer/corefx,ViktorHofer/corefx,janhenke/corefx,rjxby/corefx,cartermp/corefx,iamjasonp/corefx,Yanjing123/corefx,gregg-miskelly/corefx,kkurni/corefx,YoupHulsebos/corefx,Petermarcu/corefx,jlin177/corefx,stephenmichaelf/corefx,richlander/corefx,elijah6/corefx,mazong1123/corefx,alphonsekurian/corefx,weltkante/corefx,marksmeltzer/corefx,dotnet-bot/corefx,alexperovich/corefx,ravimeda/corefx,krk/corefx,Yanjing123/corefx,n1ghtmare/corefx,marksmeltzer/corefx,shimingsg/corefx,weltkante/corefx,stone-li/corefx,parjong/corefx,rubo/corefx,richlander/corefx,richlander/corefx,twsouthwick/corefx,gregg-miskelly/corefx,stephenmichaelf/corefx,cydhaselton/corefx,ericstj/corefx,parjong/corefx,Chrisboh/corefx,SGuyGe/corefx,weltkante/corefx,manu-silicon/corefx,BrennanConroy/corefx,MaggieTsang/corefx,wtgodbe/corefx,ViktorHofer/corefx,rahku/corefx,YoupHulsebos/corefx,vidhya-bv/corefx-sorting,Ermiar/corefx,Chrisboh/corefx,dsplaisted/corefx,twsouthwick/corefx,mazong1123/corefx,JosephTremoulet/corefx,DnlHarvey/corefx,vidhya-bv/corefx-sorting,dsplaisted/corefx,PatrickMcDonald/corefx,andyhebear/corefx,shmao/corefx,alexperovich/corefx,jlin177/corefx,mafiya69/corefx,gkhanna79/corefx,marksmeltzer/corefx,elijah6/corefx,wtgodbe/corefx,tijoytom/corefx,alexandrnikitin/corefx,rajansingh10/corefx,690486439/corefx,yizhang82/corefx,s0ne0me/corefx,pgavlin/corefx,seanshpark/corefx,alexperovich/corefx,rubo/corefx,comdiv/corefx,stephenmichaelf/corefx,akivafr123/corefx,jcme/corefx,benpye/corefx,benpye/corefx,krytarowski/corefx,nbarbettini/corefx,690486439/corefx,mmitche/corefx,shimingsg/corefx,rahku/corefx,Jiayili1/corefx,jeremymeng/corefx,mafiya69/corefx,Ermiar/corefx,khdang/corefx,jcme/corefx,gkhanna79/corefx,pgavlin/corefx,Jiayili1/corefx,pallavit/corefx,stone-li/corefx,jeremymeng/corefx,ravimeda/corefx,fgreinacher/corefx,dhoehna/corefx,the-dwyer/corefx,jeremymeng/corefx,Priya91/corefx-1,dhoehna/corefx,alphonsekurian/corefx,shimingsg/corefx,janhenke/corefx,SGuyGe/corefx,andyhebear/corefx,richlander/corefx,josguil/corefx,pgavlin/corefx,yizhang82/corefx,alphonsekurian/corefx,krk/corefx,josguil/corefx,MaggieTsang/corefx,benjamin-bader/corefx,zhenlan/corefx,s0ne0me/corefx,mazong1123/corefx,bitcrazed/corefx,ericstj/corefx,Jiayili1/corefx,nchikanov/corefx,iamjasonp/corefx,Alcaro/corefx,billwert/corefx,dhoehna/corefx,janhenke/corefx,krytarowski/corefx,cartermp/corefx,690486439/corefx,cydhaselton/corefx,fgreinacher/corefx,DnlHarvey/corefx,mmitche/corefx,krytarowski/corefx,twsouthwick/corefx,cartermp/corefx,dotnet-bot/corefx,akivafr123/corefx,Petermarcu/corefx,cydhaselton/corefx,stormleoxia/corefx,akivafr123/corefx,dotnet-bot/corefx,mazong1123/corefx,jlin177/corefx,janhenke/corefx,the-dwyer/corefx,rjxby/corefx,pallavit/corefx,nchikanov/corefx,ellismg/corefx,alphonsekurian/corefx,tijoytom/corefx,shahid-pk/corefx,mazong1123/corefx,wtgodbe/corefx,stone-li/corefx,the-dwyer/corefx,zhenlan/corefx,parjong/corefx,stephenmichaelf/corefx,bitcrazed/corefx,axelheer/corefx,stephenmichaelf/corefx,benjamin-bader/corefx,fgreinacher/corefx,ViktorHofer/corefx,shahid-pk/corefx,josguil/corefx,kkurni/corefx,vs-team/corefx,alexperovich/corefx,kkurni/corefx,pallavit/corefx,stone-li/corefx,alexperovich/corefx,manu-silicon/corefx,stephenmichaelf/corefx,Alcaro/corefx,comdiv/corefx,adamralph/corefx,nbarbettini/corefx,akivafr123/corefx,MaggieTsang/corefx,gregg-miskelly/corefx,BrennanConroy/corefx,ellismg/corefx,PatrickMcDonald/corefx,yizhang82/corefx,mellinoe/corefx,benjamin-bader/corefx,s0ne0me/corefx,andyhebear/corefx,stone-li/corefx,elijah6/corefx,jcme/corefx,JosephTremoulet/corefx,manu-silicon/corefx,gkhanna79/corefx,stormleoxia/corefx,alexandrnikitin/corefx,SGuyGe/corefx,mmitche/corefx,YoupHulsebos/corefx,jhendrixMSFT/corefx,dhoehna/corefx,mafiya69/corefx,n1ghtmare/corefx,iamjasonp/corefx,billwert/corefx,gkhanna79/corefx,tijoytom/corefx,wtgodbe/corefx,seanshpark/corefx,690486439/corefx,krk/corefx,zhenlan/corefx,JosephTremoulet/corefx,tijoytom/corefx,krytarowski/corefx,PatrickMcDonald/corefx,Jiayili1/corefx,cydhaselton/corefx,jlin177/corefx,heXelium/corefx,mokchhya/corefx,pgavlin/corefx,lggomez/corefx,the-dwyer/corefx,rjxby/corefx,YoupHulsebos/corefx,stormleoxia/corefx
src/System.Globalization/tests/DateTimeFormatInfo/DateTimeFormatInfoGetInstance.cs
src/System.Globalization/tests/DateTimeFormatInfo/DateTimeFormatInfoGetInstance.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using Xunit; namespace System.Globalization.Tests { public class TestIFormatProviderClass : IFormatProvider { public object GetFormat(Type formatType) { return this; } } public class TestIFormatProviderClass2 : IFormatProvider { public object GetFormat(Type formatType) { return new DateTimeFormatInfo(); } } public class DateTimeFormatInfoGetInstance { // PosTest1: Call GetInstance to get an DateTimeFormatInfo instance when provider is an CultureInfo instance [Fact] public void PosTest1() { DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(new CultureInfo("en-us")); Assert.NotNull(info); } // PosTest2: Call GetInstance to get an DateTimeFormatInfo instance when provider is null reference [Fact] [ActiveIssue(3421, PlatformID.AnyUnix)] public void PosTest2() { DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(null); Assert.Equal(DateTimeFormatInfo.CurrentInfo, info); } // PosTest3: Call GetInstance to get an DateTimeFormatInfo instance when provider is a DateTimeFormatInfo instance [Fact] public void PosTest3() { DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(new DateTimeFormatInfo()); Assert.NotNull(info); } // PosTest4: Call GetInstance to get an DateTimeFormatInfo instance when provider.GetFormat method supports a DateTimeFormatInfo instance [Fact] public void PosTest4() { DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(new TestIFormatProviderClass2()); Assert.NotNull(info); } // PosTest5: Call GetInstance to get an DateTimeFormatInfo instance when provider.GetFormat method does not support a DateTimeFormatInfo instance [Fact] [ActiveIssue(3421, PlatformID.AnyUnix)] public void PosTest5() { DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(new TestIFormatProviderClass()); Assert.Equal(DateTimeFormatInfo.CurrentInfo, info); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using Xunit; namespace System.Globalization.Tests { public class TestIFormatProviderClass : IFormatProvider { public object GetFormat(Type formatType) { return this; } } public class TestIFormatProviderClass2 : IFormatProvider { public object GetFormat(Type formatType) { return new DateTimeFormatInfo(); } } public class DateTimeFormatInfoGetInstance { // PosTest1: Call GetInstance to get an DateTimeFormatInfo instance when provider is an CultureInfo instance [Fact] public void PosTest1() { DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(new CultureInfo("en-us")); Assert.NotNull(info); } // PosTest2: Call GetInstance to get an DateTimeFormatInfo instance when provider is null reference [Fact] [ActiveIssue(846, PlatformID.AnyUnix)] // sporadic failure (#3421) public void PosTest2() { DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(null); Assert.Equal(DateTimeFormatInfo.CurrentInfo, info); } // PosTest3: Call GetInstance to get an DateTimeFormatInfo instance when provider is a DateTimeFormatInfo instance [Fact] public void PosTest3() { DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(new DateTimeFormatInfo()); Assert.NotNull(info); } // PosTest4: Call GetInstance to get an DateTimeFormatInfo instance when provider.GetFormat method supports a DateTimeFormatInfo instance [Fact] public void PosTest4() { DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(new TestIFormatProviderClass2()); Assert.NotNull(info); } // PosTest5: Call GetInstance to get an DateTimeFormatInfo instance when provider.GetFormat method does not support a DateTimeFormatInfo instance [Fact] public void PosTest5() { DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(new TestIFormatProviderClass()); Assert.Equal(DateTimeFormatInfo.CurrentInfo, info); } } }
mit
C#
5996d940529208aa89caad59376cba351573fcae
make this LINQ a bit more readable
TRex22/Windows-Wifi-Manager,shanselman/Windows-Wifi-Manager
WifiProfiles/Program.cs
WifiProfiles/Program.cs
using NetSh; using System; using System.Linq; namespace WifiProfiles { class Program { static void Main(string[] args) { //command line arguments officially got irritating at this point but I don't feel like bringing in a whole library. if (args.Length > 1 && args[0].ToUpperInvariant() == "DELETE" && !string.IsNullOrEmpty(args[1])) Delete(args[1]); else List(args.Length == 1 && args[0].ToUpperInvariant() == "/DELETEAUTOOPEN"); } static void Delete(string profileName) { Console.WriteLine(NetShWrapper.DeleteWifiProfile(profileName)); } static void List(bool autoDelete) { var profiles = NetShWrapper.GetWifiProfiles(); bool sawBadWifi = false; foreach (var a in profiles) { string warning = NetShWrapper.IsOpenAndAutoWifiProfile(a) ? "Warning: AUTO connect to OPEN WiFi" : String.Empty; Console.WriteLine("{0,-20} {1,10} {2,10} {3,30} ", a.Name, a.ConnectionMode, a.Authentication, warning); if (!String.IsNullOrWhiteSpace(warning)) sawBadWifi = true; } if (sawBadWifi) { if(!autoDelete) Console.WriteLine("\r\nDelete WiFi profiles that are OPEN *and* AUTO connect? [y/n]"); if (autoDelete || Console.ReadLine().Trim().ToUpperInvariant().StartsWith("Y")) { foreach (var a in profiles.Where(NetShWrapper.IsOpenAndAutoWifiProfile)) { Console.WriteLine(NetShWrapper.DeleteWifiProfile(a.Name)); } } } else { Console.WriteLine("\r\nNo WiFi profiles set to OPEN and AUTO connect were found. \r\nOption: Run with /deleteautoopen to auto delete."); } } } }
using NetSh; using System; using System.Linq; namespace WifiProfiles { class Program { static void Main(string[] args) { //command line arguments officially got irritating at this point but I don't feel like bringing in a whole library. if (args.Length > 1 && args[0].ToUpperInvariant() == "DELETE" && !string.IsNullOrEmpty(args[1])) Delete(args[1]); else List(args.Length == 1 && args[0].ToUpperInvariant() == "/DELETEAUTOOPEN"); } static void Delete(string profileName) { Console.WriteLine(NetShWrapper.DeleteWifiProfile(profileName)); } static void List(bool autoDelete) { var profiles = NetShWrapper.GetWifiProfiles(); bool sawBadWifi = false; foreach (var a in profiles) { string warning = NetShWrapper.IsOpenAndAutoWifiProfile(a) ? "Warning: AUTO connect to OPEN WiFi" : String.Empty; Console.WriteLine("{0,-20} {1,10} {2,10} {3,30} ", a.Name, a.ConnectionMode, a.Authentication, warning); if (!String.IsNullOrWhiteSpace(warning)) sawBadWifi = true; } if (sawBadWifi) { if(!autoDelete) Console.WriteLine("\r\nDelete WiFi profiles that are OPEN *and* AUTO connect? [y/n]"); if (autoDelete || Console.ReadLine().Trim().ToUpperInvariant().StartsWith("Y")) { foreach (var a in profiles.Where(a => NetShWrapper.IsOpenAndAutoWifiProfile(a))) { Console.WriteLine(NetShWrapper.DeleteWifiProfile(a.Name)); } } } else { Console.WriteLine("\r\nNo WiFi profiles set to OPEN and AUTO connect were found. \r\nOption: Run with /deleteautoopen to auto delete."); } } } }
mit
C#
f4e824fc4c0e1c7af1d81f0a765a8614194fc0c8
Update FlanGrab_FlandreBehaviour.cs
uulltt/NitoriWare
Assets/Resources/Microgames/_Finished/FlanGrab/Scripts/FlanGrab_FlandreBehaviour.cs
Assets/Resources/Microgames/_Finished/FlanGrab/Scripts/FlanGrab_FlandreBehaviour.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FlanGrab_FlandreBehaviour : MonoBehaviour { private GameObject rightArmObject; //private float xRightLimit; [SerializeField] private float bodyRotationMult; // Use this for initialization void Start () { //var microgrameScript = MicrogameController.instance.GetComponent<FlanGrab_Microgame_Behaviour>(); //xRightLimit = microgrameScript.rightLimit; rightArmObject = this.transform.FindChild("Right_Arm").gameObject; } // Update is called once per frame void Update () { if (!MicrogameController.instance.getVictoryDetermined()) { rotateRightArm(); } } void rotateRightArm() { var mouseOnScreen = CameraHelper.getCursorPosition(); var positionOnScreen = rightArmObject.transform.position; float angle = AngleBetweenTwoPoints(positionOnScreen, mouseOnScreen); if (Mathf.Abs(angle) <= 90f) { rightArmObject.transform.rotation = Quaternion.Euler(Vector3.forward * angle)); transform.rotation = Quaternion.Euler(Vector3.forward * angle * bodyRotationMult)); } } float AngleBetweenTwoPoints(Vector3 a, Vector3 b) { return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FlanGrab_FlandreBehaviour : MonoBehaviour { private GameObject rightArmObject; //private float xRightLimit; [SerializeField] private float bodyRotationMult; // Use this for initialization void Start () { //var microgrameScript = MicrogameController.instance.GetComponent<FlanGrab_Microgame_Behaviour>(); //xRightLimit = microgrameScript.rightLimit; rightArmObject = this.transform.FindChild("Right_Arm").gameObject; } // Update is called once per frame void Update () { if (!MicrogameController.instance.getVictoryDetermined()) { rotateRightArm(); } } void rotateRightArm() { var mouseOnScreen = CameraHelper.getCursorPosition(); var positionOnScreen = rightArmObject.transform.position; float angle = AngleBetweenTwoPoints(positionOnScreen, mouseOnScreen); if (-90 <= angle && angle <= 90) { rightArmObject.transform.rotation = Quaternion.Euler(new Vector3(0f, 0f, angle)); transform.rotation = Quaternion.Euler(new Vector3(0f, 0f, angle * bodyRotationMult)); } } float AngleBetweenTwoPoints(Vector3 a, Vector3 b) { return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg; } }
mit
C#
0120a5d8aa1c541b8882b0208d4eb1004db65a4d
Fix --resultFormat casing to match other parameters
mjrousos/dotnet-apiport,mjrousos/dotnet-apiport-old,Microsoft/dotnet-apiport,mjrousos/dotnet-apiport,JJVertical/dotnet-apiport,Microsoft/dotnet-apiport,twsouthwick/dotnet-apiport,twsouthwick/dotnet-apiport,conniey/dotnet-apiport,conniey/dotnet-apiport,conniey/dotnet-apiport,JJVertical/dotnet-apiport,Microsoft/dotnet-apiport
src/ApiPort/CommandLine/AnalyzeOptionSet.cs
src/ApiPort/CommandLine/AnalyzeOptionSet.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using ApiPort.Resources; using Microsoft.Fx.Portability.ObjectModel; using System.Linq; namespace ApiPort.CommandLine { internal class AnalyzeOptionSet : ServiceEndpointOptionSet { public AnalyzeOptionSet(string name) : base(name, AppCommands.AnalyzeAssemblies) { Add("f|file=", LocalizedStrings.ListOfAssembliesToAnalyze, UpdateInputAssemblies, true); Add("o|out=", LocalizedStrings.OutputFileName, e => OutputFileName = e); Add("d|description=", LocalizedStrings.DescriptionHelp, e => Description = e); Add("t|target=", LocalizedStrings.TargetsToCheckAgainst, UpdateTargets); Add("r|resultFormat=", LocalizedStrings.ResultFormatHelp, UpdateOutputFormats); Add("p|showNonPortableApis", LocalizedStrings.CmdHelpShowNonPortableApis, e => { if (e != null) { RequestFlags |= AnalyzeRequestFlags.ShowNonPortableApis; } }); Add("b|showBreakingChanges", LocalizedStrings.CmdHelpShowBreakingChanges, e => { if (e != null) { RequestFlags |= AnalyzeRequestFlags.ShowBreakingChanges; } }); Add("noDefaultIgnoreFile", LocalizedStrings.CmdHelpNoDefaultIgnoreFile, e => { if (e != null) { RequestFlags |= AnalyzeRequestFlags.NoDefaultIgnoreFile; } }); Add("i|ignoreAssemblyFile=", LocalizedStrings.CmdHelpIgnoreAssembliesFile, UpdateIgnoredAssemblyFiles); Add("s|suppressBreakingChange=", LocalizedStrings.CmdHelpSuppressBreakingChange, UpdateBreakingChangeSuppressions); } protected override bool ValidateValues() { // If nothing is set, default to ShowNonPortableApis if ((RequestFlags & (AnalyzeRequestFlags.ShowBreakingChanges | AnalyzeRequestFlags.ShowNonPortableApis)) == AnalyzeRequestFlags.None) { RequestFlags |= AnalyzeRequestFlags.ShowNonPortableApis; } // If no output formats have been supplied, default to Excel // TODO: Should probably get this from the service, not hard-coded if(!OutputFormats.Any()) { UpdateOutputFormats("Excel"); } return InputAssemblies.Any(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using ApiPort.Resources; using Microsoft.Fx.Portability.ObjectModel; using System.Linq; namespace ApiPort.CommandLine { internal class AnalyzeOptionSet : ServiceEndpointOptionSet { public AnalyzeOptionSet(string name) : base(name, AppCommands.AnalyzeAssemblies) { Add("f|file=", LocalizedStrings.ListOfAssembliesToAnalyze, UpdateInputAssemblies, true); Add("o|out=", LocalizedStrings.OutputFileName, e => OutputFileName = e); Add("d|description=", LocalizedStrings.DescriptionHelp, e => Description = e); Add("t|target=", LocalizedStrings.TargetsToCheckAgainst, UpdateTargets); Add("r|resultformat=", LocalizedStrings.ResultFormatHelp, UpdateOutputFormats); Add("p|showNonPortableApis", LocalizedStrings.CmdHelpShowNonPortableApis, e => { if (e != null) { RequestFlags |= AnalyzeRequestFlags.ShowNonPortableApis; } }); Add("b|showBreakingChanges", LocalizedStrings.CmdHelpShowBreakingChanges, e => { if (e != null) { RequestFlags |= AnalyzeRequestFlags.ShowBreakingChanges; } }); Add("noDefaultIgnoreFile", LocalizedStrings.CmdHelpNoDefaultIgnoreFile, e => { if (e != null) { RequestFlags |= AnalyzeRequestFlags.NoDefaultIgnoreFile; } }); Add("i|ignoreAssemblyFile=", LocalizedStrings.CmdHelpIgnoreAssembliesFile, UpdateIgnoredAssemblyFiles); Add("s|suppressBreakingChange=", LocalizedStrings.CmdHelpSuppressBreakingChange, UpdateBreakingChangeSuppressions); } protected override bool ValidateValues() { // If nothing is set, default to ShowNonPortableApis if ((RequestFlags & (AnalyzeRequestFlags.ShowBreakingChanges | AnalyzeRequestFlags.ShowNonPortableApis)) == AnalyzeRequestFlags.None) { RequestFlags |= AnalyzeRequestFlags.ShowNonPortableApis; } // If no output formats have been supplied, default to Excel // TODO: Should probably get this from the service, not hard-coded if(!OutputFormats.Any()) { UpdateOutputFormats("Excel"); } return InputAssemblies.Any(); } } }
mit
C#
3cba46608ab2e2ca6a095baf1cf8112010e81036
Add registration options for reference request
PowerShell/PowerShellEditorServices
src/PowerShellEditorServices.Protocol/LanguageServer/References.cs
src/PowerShellEditorServices.Protocol/LanguageServer/References.cs
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol; namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer { public class ReferencesRequest { public static readonly RequestType<ReferencesParams, Location[], object, TextDocumentRegistrationOptions> Type = RequestType<ReferencesParams, Location[], object, TextDocumentRegistrationOptions>.Create("textDocument/references"); } public class ReferencesParams : TextDocumentPosition { public ReferencesContext Context { get; set; } } public class ReferencesContext { public bool IncludeDeclaration { get; set; } } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol; namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer { public class ReferencesRequest { public static readonly RequestType<ReferencesParams, Location[], object, object> Type = RequestType<ReferencesParams, Location[], object, object>.Create("textDocument/references"); } public class ReferencesParams : TextDocumentPosition { public ReferencesContext Context { get; set; } } public class ReferencesContext { public bool IncludeDeclaration { get; set; } } }
mit
C#
b556eb96da1ec359efef8b3184c9d95cc0faf590
同步 .net 4.5 项目版本号
JeffreySu/Senparc.WebSocket
src/Senparc.WebSocket/Senparc.WebSocket/Properties/AssemblyInfo.cs
src/Senparc.WebSocket/Senparc.WebSocket/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 //[assembly: AssemblyTitle("Senparc.WebSocket")] //[assembly: AssemblyDescription("")] //[assembly: AssemblyConfiguration("")] //[assembly: AssemblyCompany("")] //[assembly: AssemblyProduct("Senparc.WebSocket")] //[assembly: AssemblyCopyright("Copyright © 2018")] //[assembly: AssemblyTrademark("")] //[assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("b745f5f5-9120-4d56-a86d-ed34eadb703c")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.8.0.*")] //[assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 //[assembly: AssemblyTitle("Senparc.WebSocket")] //[assembly: AssemblyDescription("")] //[assembly: AssemblyConfiguration("")] //[assembly: AssemblyCompany("")] //[assembly: AssemblyProduct("Senparc.WebSocket")] //[assembly: AssemblyCopyright("Copyright © 2018")] //[assembly: AssemblyTrademark("")] //[assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("b745f5f5-9120-4d56-a86d-ed34eadb703c")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.7.2.*")] //[assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
10e66e24e962b3499edc2ed73050930ab8735379
Add channel state None (CS_NONE)
pragmatrix/NEventSocket,pragmatrix/NEventSocket
src/NEventSocket/FreeSwitch/ChannelState.cs
src/NEventSocket/FreeSwitch/ChannelState.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ChannelState.cs" company="Dan Barua"> // (C) Dan Barua and contributors. Licensed under the Mozilla Public License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace NEventSocket.FreeSwitch { /// <summary> /// Represents the state of a Channel /// </summary> public enum ChannelState { #pragma warning disable 1591 New, Init, Routing, SoftExecute, Execute, ExchangeMedia, Park, ConsumeMedia, Hibernate, Reset, Hangup, Done, Destroy, Reporting, None #pragma warning restore 1591 } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ChannelState.cs" company="Dan Barua"> // (C) Dan Barua and contributors. Licensed under the Mozilla Public License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace NEventSocket.FreeSwitch { /// <summary> /// Represents the state of a Channel /// </summary> public enum ChannelState { #pragma warning disable 1591 New, Init, Routing, SoftExecute, Execute, ExchangeMedia, Park, ConsumeMedia, Hibernate, Reset, Hangup, Done, Destroy, Reporting #pragma warning restore 1591 } }
mpl-2.0
C#
70886313a2cf9ad520fe1a8caea4476884b0393d
Fix the bug cannot get correct parameter from command line
mdavid/SuperSocket,mdavid/SuperSocket,mdavid/SuperSocket
SocketServiceCore/Command/CommandInfo.cs
SocketServiceCore/Command/CommandInfo.cs
using System; using System.Collections.Generic; using System.Text; namespace SuperSocket.SocketServiceCore.Command { public class CommandInfo { public CommandInfo() { } public CommandInfo(string cmdLine) { int pos = cmdLine.IndexOf(' '); if (pos > 0) { m_Name = cmdLine.Substring(0, pos); m_Param = cmdLine.Substring(pos + 1); m_Parmaters = m_Param.Split(' '); } else { m_Name = cmdLine; } } private string m_Tag = string.Empty; public string Tag { get { return m_Tag; } set { m_Tag = value; } } private string m_Name; public string Name { get { return m_Name; } set { m_Name = value; } } private string m_Param; public string Param { get { return m_Param; } set { m_Param = value; } } private string[] m_Parmaters; public string[] Parameters { get { return m_Parmaters; } set { m_Parmaters = value; } } public string GetFirstParam() { return GetParamemterByIndex(0); } private string GetParamemterByIndex(int index) { if (m_Parmaters == null || m_Parmaters.Length <= index) return string.Empty; return m_Parmaters[index]; } public string this[int index] { get { return GetParamemterByIndex(index); } } } }
using System; using System.Collections.Generic; using System.Text; namespace SuperSocket.SocketServiceCore.Command { public class CommandInfo { public CommandInfo() { } public CommandInfo(string cmdLine) { int pos = cmdLine.IndexOf(' '); if (pos > 0) { m_Name = cmdLine.Substring(0, pos); m_Param = cmdLine.Substring(pos + 1); m_Parmaters = m_Param.Split(' '); } else { m_Name = cmdLine; } } private string m_Tag = string.Empty; public string Tag { get { return m_Tag; } set { m_Tag = value; } } private string m_Name; public string Name { get { return m_Name; } set { m_Name = value; } } private string m_Param; public string Param { get { return m_Param; } set { m_Param = value; } } private string[] m_Parmaters; public string[] Parameters { get { return m_Parmaters; } set { m_Parmaters = value; } } public string GetFirstParam() { return GetParamemterByIndex(0); } private string GetParamemterByIndex(int index) { if (m_Parmaters == null || m_Parmaters.Length <= index) return string.Empty; return m_Parmaters[index]; } public string this[int index] { get { return GetParamemterByIndex(0); } } } }
apache-2.0
C#
62a8b21760f7ad1026b617d34a03e98feec4547f
remove readonly attribute when trying to delete files
fandrei/AppMetrics,fandrei/AppMetrics
AgentService/FileUtil.cs
AgentService/FileUtil.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; namespace AppMetrics.AgentService { public static class FileUtil { public static void SetAttributes(string fileName, FileAttributes attr) { File.SetAttributes(fileName, File.GetAttributes(fileName) | attr); } public static void ResetAttributes(string fileName, FileAttributes attr) { if (HasAttributes(fileName, attr)) File.SetAttributes(fileName, File.GetAttributes(fileName) & ~attr); } public static bool HasAttributes(string fileName, FileAttributes attr) { return ((File.GetAttributes(fileName) & attr) == attr); } public static void DeleteAllFiles(string path) { var repeatCount = 10; while (true) { try { foreach (var file in Directory.GetFiles(path)) { ResetAttributes(file, FileAttributes.ReadOnly); File.Delete(file); } break; } catch (UnauthorizedAccessException exc) { repeatCount--; if (repeatCount <= 0) throw; } Thread.Sleep(TimeSpan.FromSeconds(1)); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; namespace AppMetrics.AgentService { public static class FileUtil { public static void DeleteAllFiles(string path) { var repeatCount = 10; while (true) { try { foreach (var file in Directory.GetFiles(path)) { File.Delete(file); } break; } catch (UnauthorizedAccessException exc) { repeatCount--; if (repeatCount <= 0) throw; } Thread.Sleep(TimeSpan.FromSeconds(1)); } } } }
apache-2.0
C#
572e07ff7b24c74f5255ff6919df1772c607367a
Make the CronFormatException class serializable on .NET Framework
HangfireIO/Cronos
src/Cronos/CronFormatException.cs
src/Cronos/CronFormatException.cs
using System; namespace Cronos { /// <summary> /// Represents an exception that's thrown, when invalid Cron expression is given. /// </summary> #if !NETSTANDARD1_0 [Serializable] #endif public class CronFormatException : FormatException { /// <summary> /// Initializes a new instance of the <see cref="CronFormatException"/> class with /// the given message. /// </summary> public CronFormatException(string message) : base(message) { } internal CronFormatException(CronField field, string message) : this($"{field}: {message}") { } } }
using System; namespace Cronos { /// <summary> /// Represents an exception that's thrown, when invalid Cron expression is given. /// </summary> public class CronFormatException : FormatException { /// <summary> /// Initializes a new instance of the <see cref="CronFormatException"/> class with /// the given message. /// </summary> public CronFormatException(string message) : base(message) { } internal CronFormatException(CronField field, string message) : this($"{field}: {message}") { } } }
mit
C#
657e7f9ad1925e48cace4801d9681f13c218f1ad
Update SerializationTests.cs
tiksn/TIKSN-Framework
TIKSN.UnitTests.Shared/Serialization/Numerics/SerializationTests.cs
TIKSN.UnitTests.Shared/Serialization/Numerics/SerializationTests.cs
using FluentAssertions; using System; using System.Numerics; using Xunit; namespace TIKSN.Serialization.Numerics.Tests { public class SerializationTests { [Fact] public void DeserializeSerializeUnsignedBigInteger() { var rng = new Random(); UnsignedBigIntegerBinarySerializer serializer = new UnsignedBigIntegerBinarySerializer(); UnsignedBigIntegerBinaryDeserializer deserializer = new UnsignedBigIntegerBinaryDeserializer(); for (int i = 0; i < 10; i++) { var number = BigInteger.One; number *= rng.Next(); number *= rng.Next(); number *= rng.Next(); number *= rng.Next(); var bytes = serializer.Serialize(number); var recovered = deserializer.Deserialize(bytes); var recoveredBytes = serializer.Serialize(recovered); recovered.Should().Be(number); recoveredBytes.Should().BeEquivalentTo(bytes); } } } }
using FluentAssertions; using System; using System.Numerics; using Xunit; namespace TIKSN.Serialization.Numerics.Tests { public class SerializationTests { [Fact] public void DeserializeSerializeUnsignedBigInteger() { var rng = new Random(); UnsignedBigIntegerBinarySerializer serializer = new UnsignedBigIntegerBinarySerializer(); UnsignedBigIntegerBinaryDeserializer deserializer = new UnsignedBigIntegerBinaryDeserializer(); var number = BigInteger.One; number *= rng.Next(); number *= rng.Next(); number *= rng.Next(); number *= rng.Next(); var bytes = serializer.Serialize(number); var recovered = deserializer.Deserialize(bytes); recovered.Should().Be(number); } } }
mit
C#
71c2c02ccf8da0765d21a79bf9bcfe1dd87f1544
rename offset variable
HouseBreaker/Shameless
Shameless/Utils/CDNUtils.cs
Shameless/Utils/CDNUtils.cs
using System; using System.Linq; namespace Shameless.Utils { using System.Net; public static class CDNUtils { public static long GetTitleSize(string titleId) { // translated from FunKeyCIA var cdnUrl = "http://ccs.cdn.c.shop.nintendowifi.net/ccs/download/" + titleId.ToUpper(); byte[] tmd; using (var client = new WebClient()) { tmd = client.DownloadData(cdnUrl + "/tmd"); } const int TikOffset = 0x140; var contentCount = Convert.ToInt32(BitConversion.BytesToHex(tmd.Skip(TikOffset + 0x9E).Take(2)), 16); long size = 0; for (int i = 0; i < contentCount; i++) { var contentOffset = 0xB04 + 0x30 * i; var contentId = BitConversion.BytesToHex(tmd.Skip(contentOffset).Take(4)); try { var req = WebRequest.Create(cdnUrl + "/" + contentId); using (var resp = req.GetResponse()) { long currentSize; if (long.TryParse(resp.Headers.Get("Content-Length"), out currentSize)) { size += currentSize; } } } catch (WebException) { } } return size; } } }
using System; using System.Linq; namespace Shameless.Utils { using System.Net; public static class CDNUtils { public static long GetTitleSize(string titleId) { // translated from FunKeyCIA var cdnUrl = "http://ccs.cdn.c.shop.nintendowifi.net/ccs/download/" + titleId.ToUpper(); byte[] tmd; using (var client = new WebClient()) { tmd = client.DownloadData(cdnUrl + "/tmd"); } const int TikOffset = 0x140; var contentCount = Convert.ToInt32(BitConversion.BytesToHex(tmd.Skip(TikOffset + 0x9E).Take(2)), 16); long size = 0; for (int i = 0; i < contentCount; i++) { var cOffs = 0xB04 + 0x30 * i; var contentId = BitConversion.BytesToHex(tmd.Skip(cOffs).Take(4)); try { var req = WebRequest.Create(cdnUrl + "/" + contentId); using (var resp = req.GetResponse()) { long currentSize; if (long.TryParse(resp.Headers.Get("Content-Length"), out currentSize)) { size += currentSize; } } } catch (WebException) { } } return size; } } }
mit
C#
6e8f0332d0d4785a39caaef39944be62a9731678
use static current of exception handler when prop injection is not working
bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework
src/CSharpClient/Bit.CSharpClient.Prism/ViewModel/Implementations/BitPrismLogger.cs
src/CSharpClient/Bit.CSharpClient.Prism/ViewModel/Implementations/BitPrismLogger.cs
#define Debug using Bit.ViewModel.Contracts; using Prism.Logging; using System; using System.Collections.Generic; using System.Diagnostics; namespace Bit.ViewModel.Implementations { public class BitPrismLogger : ILogger { public virtual IExceptionHandler ExceptionHandler { get; set; } public virtual void Log(string message, IDictionary<string, string> properties) { if (Debugger.IsAttached) Debug.WriteLine(message); } public virtual void Log(string message, Category category, Priority priority) { if (category == Category.Exception) { Report(new Exception(message), new Dictionary<string, string> { { nameof(category), category.ToString() }, { nameof(priority), priority.ToString() } }); } else if (Debugger.IsAttached) { Debug.WriteLine(message); } } public virtual void Report(Exception ex, IDictionary<string, string> properties) { BitExceptionHandler.Current.OnExceptionReceived(ex, properties); } public virtual void TrackEvent(string name, IDictionary<string, string> properties) { } } }
#define Debug using Bit.ViewModel.Contracts; using Prism.Logging; using System; using System.Collections.Generic; using System.Diagnostics; namespace Bit.ViewModel.Implementations { public class BitPrismLogger : ILogger { public virtual IExceptionHandler ExceptionHandler { get; set; } public virtual void Log(string message, IDictionary<string, string> properties) { if (Debugger.IsAttached) Debug.WriteLine(message); } public virtual void Log(string message, Category category, Priority priority) { if (category == Category.Exception) { Report(new Exception(message), new Dictionary<string, string> { { nameof(category), category.ToString() }, { nameof(priority), priority.ToString() } }); } else if (Debugger.IsAttached) { Debug.WriteLine(message); } } public virtual void Report(Exception ex, IDictionary<string, string> properties) { ExceptionHandler.OnExceptionReceived(ex, properties); } public virtual void TrackEvent(string name, IDictionary<string, string> properties) { } } }
mit
C#
d03a92f8586fe84d28a388b4fdb3ef6d40628ca0
Add "mine" args
quantumagi/StratisBitcoinFullNode,DogaOztuzun/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,Derrick-/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode
Stratis.BitcoinD/Program.cs
Stratis.BitcoinD/Program.cs
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Console; using Stratis.Bitcoin; using Stratis.Bitcoin.Configuration; using Stratis.Bitcoin.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Stratis.BitcoinD { public class Program { public static void Main(string[] args) { Logs.Configure(new LoggerFactory().AddConsole(LogLevel.Trace, false)); NodeArgs nodeArgs = NodeArgs.GetArgs(args); FullNode node = new FullNode(nodeArgs); CancellationTokenSource cts = new CancellationTokenSource(); new Thread(() => { Console.WriteLine("Press one key to stop"); Console.ReadLine(); node.Dispose(); }) { IsBackground = true //so the process terminate }.Start(); if (args.Any(a => a.Contains("mine"))) { new Thread(() => { Thread.Sleep(10000); // let the node start while (!node.IsDisposed) { Thread.Sleep(1000); // wait 1 sec // generate 1 block node.Miner.GenerateBlocks(new Stratis.Bitcoin.Miner.ReserveScript() { reserveSfullNodecript = new NBitcoin.Key().ScriptPubKey }, 1, 100000000, false); Console.WriteLine("mined tip at: " + node?.Chain.Tip.Height); } }) { IsBackground = true //so the process terminate }.Start(); } node.Start(); node.WaitDisposed(); node.Dispose(); } } }
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Console; using Stratis.Bitcoin; using Stratis.Bitcoin.Configuration; using Stratis.Bitcoin.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Stratis.BitcoinD { public class Program { public static void Main(string[] args) { Logs.Configure(new LoggerFactory().AddConsole(LogLevel.Trace, false)); NodeArgs nodeArgs = NodeArgs.GetArgs(args); FullNode node = new FullNode(nodeArgs); CancellationTokenSource cts = new CancellationTokenSource(); new Thread(() => { Console.WriteLine("Press one key to stop"); Console.ReadLine(); node.Dispose(); }) { IsBackground = true //so the process terminate }.Start(); node.Start(); node.WaitDisposed(); node.Dispose(); } } }
mit
C#
3c3aa506296911c0ad69aaac72f68ea3dccc184f
use new base constructor to pass TypeInfo and PropertySet
6bee/aqua-compare,6bee/aqua-graphcompare
src/Aqua.GraphCompare/DynamicObjectWithOriginalReference.cs
src/Aqua.GraphCompare/DynamicObjectWithOriginalReference.cs
// Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information. namespace Aqua.GraphCompare { using Aqua.Dynamic; public sealed class DynamicObjectWithOriginalReference : DynamicObject { private readonly object _originalObject; public DynamicObjectWithOriginalReference(DynamicObject dynamicObject, object originalObject) : base(dynamicObject.Type, dynamicObject.Properties) { _originalObject = originalObject; } public DynamicObjectWithOriginalReference(object obj, IDynamicObjectMapper mapper = null) : base(obj, mapper) { _originalObject = obj; } /// <summary> /// Gets the object instance represented by this dynamic object /// </summary> public object OriginalObject => _originalObject; } }
// Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information. namespace Aqua.GraphCompare { using Aqua.Dynamic; public sealed class DynamicObjectWithOriginalReference : DynamicObject { private readonly object _originalObject; public DynamicObjectWithOriginalReference(DynamicObject dynamicObject, object originalObject) : base(dynamicObject, deepCopy: false) { _originalObject = originalObject; } public DynamicObjectWithOriginalReference(object obj, IDynamicObjectMapper mapper = null) : base(obj, mapper) { _originalObject = obj; } /// <summary> /// Gets the object instance represented by this dynamic object /// </summary> public object OriginalObject { get { return _originalObject; } } } }
mit
C#
aeb6d858032d0a6487c21fc8776eb290b166d3f3
Update Path2DPathEffect.cs
wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D
src/Draw2D.ViewModels/Style/PathEffects/Path2DPathEffect.cs
src/Draw2D.ViewModels/Style/PathEffects/Path2DPathEffect.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Runtime.Serialization; using Spatial; namespace Draw2D.ViewModels.Style.PathEffects { [DataContract(IsReference = true)] public class Path2DPathEffect : ViewModelBase, IPathEffect { private Matrix _matrix; private string _path; [DataMember(IsRequired = false, EmitDefaultValue = false)] public Matrix Matrix { get => _matrix; set => Update(ref _matrix, value); } [DataMember(IsRequired = false, EmitDefaultValue = false)] public string Path { get => _path; set => Update(ref _path, value); } public Path2DPathEffect() { } public Path2DPathEffect(Matrix matrix, string path) { this.Matrix = matrix; this.Path = path; } public static IPathEffect MakeTile() { var matrix = Matrix.MakeFrom(Matrix2.Scale(15, 15)); var path = "M-15 -15L15 -15L15 15L-15 15L-15 -15Z"; return new Path2DPathEffect(matrix, path) { Title = "2DPathTile" }; } public object Copy(Dictionary<object, object> shared) { return new Path2DPathEffect() { Title = this.Title, Matrix = (Matrix)this.Matrix.Copy(shared), Path = this.Path }; } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Runtime.Serialization; using Spatial; namespace Draw2D.ViewModels.Style.PathEffects { [DataContract(IsReference = true)] public class Path2DPathEffect : ViewModelBase, IPathEffect { private Matrix _matrix; private string _path; [DataMember(IsRequired = false, EmitDefaultValue = false)] public Matrix Matrix { get => _matrix; set => Update(ref _matrix, value); } [DataMember(IsRequired = false, EmitDefaultValue = false)] public string Path { get => _path; set => Update(ref _path, value); } public Path2DPathEffect() { } public Path2DPathEffect(Matrix matrix, string path) { this.Matrix = matrix; this.Path = path; } public static IPathEffect MakeTile() { var matrix = Matrix.MakeFrom(Matrix2.Scale(30, 30)); var path = "M-15 -15L15 -15L15 15L-15 15L-15 -15Z"; return new Path2DPathEffect(matrix, path) { Title = "2DPathTile" }; } public object Copy(Dictionary<object, object> shared) { return new Path2DPathEffect() { Title = this.Title, Matrix = (Matrix)this.Matrix.Copy(shared), Path = this.Path }; } } }
mit
C#
d6c86f5faaeb8dd6d0e8ce7a633ae1cb08bb436a
edit Player.cs
TelerikAcademy2015/TelerikDefence
TowerDefense/Main/Player.cs
TowerDefense/Main/Player.cs
using System; namespace TowerDefense.Main { public class Player : PropertyChangedAwaredObject { private string name; public string Name { get { return this.name; } set { if (string.IsNullOrEmpty(value)) { throw new InvalidNameException("Name cannot be null"); } this.name = value; } } private int score; public int Score { get { return this.score; } set { this.score = value; this.OnPropertyChanged("Score"); } } private int money; public int Money { get { return this.money; } set { this.money = value; this.OnPropertyChanged("Money"); } } private int lives; public int Lives { get { return this.lives; } set { this.lives = value; this.OnPropertyChanged("Lives"); } } public Player() { this.Name = String.Empty; this.Score = 0; this.Money = 200; this.Lives = 10; } } }
using System; namespace TowerDefense.Main { public class Player : PropertyChangedAwaredObject { private string name; public string Name { get { return this.name; } set { if (value == null) { throw new InvalidNameException("Name cannot be null"); } this.name = value; } } private int score; public int Score { get { return this.score; } set { this.score = value; this.OnPropertyChanged("Score"); } } private int money; public int Money { get { return this.money; } set { this.money = value; this.OnPropertyChanged("Money"); } } private int lives; public int Lives { get { return this.lives; } set { this.lives = value; this.OnPropertyChanged("Lives"); } } public Player() { this.Name = String.Empty; this.Score = 0; this.Money = 200; this.Lives = 10; } } }
mit
C#
d7c04cddefaf1868c2b14dac26dd25a601c58d05
Fix for no soldier foudn on nav component
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Models/NavigationViewComponent.cs
Battery-Commander.Web/Models/NavigationViewComponent.cs
using BatteryCommander.Web.Controllers; using BatteryCommander.Web.Services; using Microsoft.AspNetCore.Mvc; using System; using System.Threading.Tasks; namespace BatteryCommander.Web.Models { public class NavigationViewComponent : ViewComponent { private readonly Database db; public Soldier Soldier { get; private set; } public Boolean ShowNavigation => Soldier != null && !String.Equals(nameof(HomeController.PrivacyAct), RouteData.Values["action"]); public NavigationViewComponent(Database db) { this.db = db; } public async Task<IViewComponentResult> InvokeAsync() { Soldier = await UserService.FindAsync(db, UserClaimsPrincipal); return View(this); } } }
using BatteryCommander.Web.Controllers; using BatteryCommander.Web.Services; using Microsoft.AspNetCore.Mvc; using System; using System.Threading.Tasks; namespace BatteryCommander.Web.Models { public class NavigationViewComponent : ViewComponent { private readonly Database db; public Soldier Soldier { get; private set; } public Boolean ShowNavigation => !String.Equals(nameof(HomeController.PrivacyAct), RouteData.Values["action"]); public NavigationViewComponent(Database db) { this.db = db; } public async Task<IViewComponentResult> InvokeAsync() { Soldier = await UserService.FindAsync(db, UserClaimsPrincipal); return View(this); } } }
mit
C#
b103043f678a801d7d42f2e1d784f559e4af954a
fix usings
DimitarDKirov/Forum-Paulo-Coelho,DimitarDKirov/Forum-Paulo-Coelho,DimitarDKirov/Forum-Paulo-Coelho
Forum-Paulo-Coelho/ForumSystem.Api/Results/ChallengeResult.cs
Forum-Paulo-Coelho/ForumSystem.Api/Results/ChallengeResult.cs
namespace ForumSystem.Api.Results { using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; public class ChallengeResult : IHttpActionResult { public ChallengeResult(string loginProvider, ApiController controller) { LoginProvider = loginProvider; Request = controller.Request; } public string LoginProvider { get; set; } public HttpRequestMessage Request { get; set; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { Request.GetOwinContext().Authentication.Challenge(LoginProvider); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized); response.RequestMessage = Request; return Task.FromResult(response); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace ForumSystem.Api.Results { public class ChallengeResult : IHttpActionResult { public ChallengeResult(string loginProvider, ApiController controller) { LoginProvider = loginProvider; Request = controller.Request; } public string LoginProvider { get; set; } public HttpRequestMessage Request { get; set; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { Request.GetOwinContext().Authentication.Challenge(LoginProvider); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized); response.RequestMessage = Request; return Task.FromResult(response); } } }
mit
C#
38cfe1e3213220ca6183e1fa16a63d57ee2b5890
use expression body
paybyphone/statsd-helper-webapi
StatsDHelper.WebApi.Tests.Integration/FakeActionDescriptor.cs
StatsDHelper.WebApi.Tests.Integration/FakeActionDescriptor.cs
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Controllers; namespace StatsDHelper.WebApi.Tests.Integration { public class FakeActionDescriptor : HttpActionDescriptor { private string _actionName = "ActionName"; public FakeActionDescriptor() : base(new HttpControllerDescriptor(new HttpConfiguration(), "ControllerName", typeof(object))) { } public override Collection<HttpParameterDescriptor> GetParameters() { throw new NotImplementedException(); } public override Task<object> ExecuteAsync(HttpControllerContext controllerContext, IDictionary<string, object> arguments, CancellationToken cancellationToken) { throw new NotImplementedException(); } public override string ActionName => _actionName; public void SetActionName(string actionName) { _actionName = actionName; } public override Type ReturnType { get { throw new NotImplementedException(); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Controllers; namespace StatsDHelper.WebApi.Tests.Integration { public class FakeActionDescriptor : HttpActionDescriptor { private string _actionName = "ActionName"; public FakeActionDescriptor() : base(new HttpControllerDescriptor(new HttpConfiguration(), "ControllerName", typeof(object))) { } public override Collection<HttpParameterDescriptor> GetParameters() { throw new NotImplementedException(); } public override Task<object> ExecuteAsync(HttpControllerContext controllerContext, IDictionary<string, object> arguments, CancellationToken cancellationToken) { throw new NotImplementedException(); } public override string ActionName { get { return _actionName; } } public void SetActionName(string actionName) { _actionName = actionName; } public override Type ReturnType { get { throw new NotImplementedException(); } } } }
apache-2.0
C#
74eef72f03a630bf6f9e11a5e410032e21a47fc8
Update MessagePackSerializer.cs
tiksn/TIKSN-Framework
TIKSN.Core/Serialization/MessagePack/MessagePackSerializer.cs
TIKSN.Core/Serialization/MessagePack/MessagePackSerializer.cs
using MsgPack.Serialization; using System.IO; namespace TIKSN.Serialization.MessagePack { public class MessagePackSerializer : SerializerBase<byte[]> { private readonly SerializationContext _serializationContext; public MessagePackSerializer(SerializationContext serializationContext) { _serializationContext = serializationContext; } protected override byte[] SerializeInternal<T>(T obj) { var serializer = _serializationContext.GetSerializer(obj.GetType()); using (var stream = new MemoryStream()) { serializer.Pack(stream, obj); return stream.ToArray(); } } } }
using MsgPack.Serialization; using System.IO; namespace TIKSN.Serialization.MessagePack { public class MessagePackSerializer : SerializerBase<byte[]> { private readonly SerializationContext _serializationContext; public MessagePackSerializer(SerializationContext serializationContext) { _serializationContext = serializationContext; } protected override byte[] SerializeInternal(object obj) { var serializer = _serializationContext.GetSerializer(obj.GetType()); using (var stream = new MemoryStream()) { serializer.Pack(stream, obj); return stream.ToArray(); } } } }
mit
C#
b47a7eccfd2e6e0ab765b4d31d0abfde91377c7e
Copy change on the logged in page
SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers
src/SFA.DAS.EmployerUsers.Web/Views/Login/AuthorizeResponse.cshtml
src/SFA.DAS.EmployerUsers.Web/Views/Login/AuthorizeResponse.cshtml
@model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel @{ ViewBag.PageID = "authorize-response"; ViewBag.Title = "Login Successful"; ViewBag.HideSigninLink = "true"; } <h1 class="heading-xlarge">Login successful</h1> <form id="mainForm" method="post" action="@Model.ResponseFormUri"> <div id="autoRedirect" style="display: none;">Please wait...</div> @Html.Raw(Model.ResponseFormFields) <div id="manualLoginContainer"> <p>Please click the continue button to complete your login.</p> <button type="submit" class="button" autofocus="autofocus">Continue</button> </div> </form> @section scripts { <script src="@Url.Content("~/Scripts/AuthorizeResponse.js")"></script> }
@model IdentityServer3.Core.ViewModels.AuthorizeResponseViewModel @{ ViewBag.PageID = "authorize-response"; ViewBag.Title = "Login Successful"; ViewBag.HideSigninLink = "true"; } <h1 class="heading-xlarge">Login successful</h1> <form id="mainForm" method="post" action="@Model.ResponseFormUri"> <div id="autoRedirect" style="display: none;">Please wait...</div> @Html.Raw(Model.ResponseFormFields) <div id="manualLoginContainer"> <p>It appears you do not have javascript enabled. Please click the continue button to complete your login.</p> <button type="submit" class="button" autofocus="autofocus">Continue</button> </div> </form> @section scripts { <script src="@Url.Content("~/Scripts/AuthorizeResponse.js")"></script> }
mit
C#
a16a978b5918a1b3685c24ab73d96888999a59ac
Update version to 0.0.5
ihtfw/TeamViewer.QuickSupport.Integration
src/TeamViewer.QuickSupport.Integration/Properties/AssemblyInfo.cs
src/TeamViewer.QuickSupport.Integration/Properties/AssemblyInfo.cs
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("TeamViewer.QuickSupport.Integration")] [assembly: AssemblyDescription("TeamViewer QuickSupport Integration")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ihtfw")] [assembly: AssemblyProduct("TeamViewer.QuickSupport.Integration")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("045afa80-dd2a-4fdf-b6a3-3b035dd14158")] // 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("0.0.5")] [assembly: AssemblyFileVersion("0.0.5")]
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("TeamViewer.QuickSupport.Integration")] [assembly: AssemblyDescription("TeamViewer QuickSupport Integration")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ihtfw")] [assembly: AssemblyProduct("TeamViewer.QuickSupport.Integration")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("045afa80-dd2a-4fdf-b6a3-3b035dd14158")] // 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("0.0.4")] [assembly: AssemblyFileVersion("0.0.4")]
mit
C#
217f259b0e98d641ce95cdc9c058add49073e6bb
Remove Analytics from Dashboard
tommcclean/PortalCMS,tommcclean/PortalCMS,tommcclean/PortalCMS
Portal.CMS.Web/Areas/Admin/Views/Dashboard/Index.cshtml
Portal.CMS.Web/Areas/Admin/Views/Dashboard/Index.cshtml
@model Portal.CMS.Web.Areas.Admin.ViewModels.Dashboard.DashboardViewModel @using Portal.CMS.Web.Areas.Admin.Helpers; @using Portal.CMS.Entities.Entities.Posts; @using Portal.CMS.Entities.Entities.Analytics; @{ ViewBag.Title = "Portal CMS"; ViewBag.Icon = "/Areas/Admin/Content/Images/icon-dashboard.png"; } <link href="~/Areas/Admin/Content/Styles/Pages/dashboard.css" rel="stylesheet" /> <div class="row"> @Html.Partial("_Welcome") @Html.Partial("_MyAccount") @Html.Partial("_LatestPost", new ViewDataDictionary(Model.LatestPost)) @Html.Partial("_LatestComments", new ViewDataDictionary(Model.LatestComments)) @Html.Partial("_MediaManager", new ViewDataDictionary(Model.Media)) </div>
@model Portal.CMS.Web.Areas.Admin.ViewModels.Dashboard.DashboardViewModel @using Portal.CMS.Web.Areas.Admin.Helpers; @using Portal.CMS.Entities.Entities.Posts; @using Portal.CMS.Entities.Entities.Analytics; @{ ViewBag.Title = "Portal CMS"; ViewBag.Icon = "/Areas/Admin/Content/Images/icon-dashboard.png"; } <link href="~/Areas/Admin/Content/Styles/Pages/dashboard.css" rel="stylesheet" /> <div class="row"> @Html.Partial("_Welcome") @Html.Partial("_MyAccount") @Html.Partial("_LatestPost", new ViewDataDictionary(Model.LatestPost)) @Html.Partial("_LatestComments", new ViewDataDictionary(Model.LatestComments)) @Html.Partial("_MediaManager", new ViewDataDictionary(Model.Media)) @Html.Action("TopPages", "Analytics", new { chartSize = ChartSize.Half, timePeriod = TimePeriod.All }) @Html.Action("TopPosts", "Analytics", new { chartSize = ChartSize.Half, timePeriod = TimePeriod.All }) </div>
mit
C#
743854a5334bb88d834436185489c5ca0b5af5d5
test commit
abmes/UnityExtensions
Semba.UnityExtensions/UnityContainerExtensionMethods.cs
Semba.UnityExtensions/UnityContainerExtensionMethods.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Practices.Unity; namespace Semba.UnityExtensions { public static class UnityContainerExtensionMethods { public static IUnityContainer RegisterTypeSingleton<TFrom, TTo>(this IUnityContainer container, params InjectionMember[] injectionMembers) where TTo : TFrom { return container.RegisterType<TFrom, TTo>(new ContainerControlledLifetimeManager(), injectionMembers); } public static IUnityContainer RegisterTypeSingleton<T>(this IUnityContainer container, params InjectionMember[] injectionMembers) { return container.RegisterType<T>(new ContainerControlledLifetimeManager(), injectionMembers); } public static IUnityContainer RegisterIEnumerable(this IUnityContainer container) { return container.RegisterType(typeof(IEnumerable<>), new InjectionFactory((c, t, n) => c.ResolveAll(t.GetGenericArguments().Single()))); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Practices.Unity; namespace Semba.UnityExtensions { public static class UnityContainerExtensionMethods { public static IUnityContainer RegisterTypeSingleton<TFrom, TTo>(this IUnityContainer container, params InjectionMember[] injectionMembers) where TTo : TFrom { return container.RegisterType<TFrom, TTo>(new ContainerControlledLifetimeManager(), injectionMembers); } public static IUnityContainer RegisterTypeSingleton<T>(this IUnityContainer container, params InjectionMember[] injectionMembers) { return container.RegisterType<T>(new ContainerControlledLifetimeManager(), injectionMembers); } public static IUnityContainer RegisterIEnumerable(this IUnityContainer container) { return container.RegisterType(typeof(IEnumerable<>), new InjectionFactory((c, t, n) => c.ResolveAll(t.GetGenericArguments().Single()))); } } }
mit
C#
83b99fd56fc320e2e853ff3601b969444fc09c8f
remove unnecessary double check
PedDavid/qip,PedDavid/qip,PedDavid/qip
Server/Authorization/Handlers/BoardPermissionHandler.cs
Server/Authorization/Handlers/BoardPermissionHandler.cs
using Authorization.Requirements; using Authorization.Resources; using API.Interfaces.IServices; using IODomain.Output; using Microsoft.AspNetCore.Authorization; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using API.Interfaces.ServicesExceptions; namespace Authorization.Handlers { public class BoardPermissionHandler : AuthorizationHandler<BoardPermissionRequirement, BoardRequest> { private readonly IUsersBoardsService _usersBoardsService; public BoardPermissionHandler(IUsersBoardsService usersBoardsService) { _usersBoardsService = usersBoardsService; } protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, BoardPermissionRequirement requirement, BoardRequest resource) { if(context.User == null || resource == null) { return; } Claim nameIdentifierClaim = context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier); string userId = nameIdentifierClaim?.Value; OutBoardPermission permission = await _usersBoardsService.GetPermissionAsync(userId, resource.BoardId); if(permission >= requirement.Permission) { context.Succeed(requirement); } } } }
using Authorization.Requirements; using Authorization.Resources; using API.Interfaces.IServices; using IODomain.Output; using Microsoft.AspNetCore.Authorization; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using API.Interfaces.ServicesExceptions; namespace Authorization.Handlers { public class BoardPermissionHandler : AuthorizationHandler<BoardPermissionRequirement, BoardRequest> { private readonly IUsersBoardsService _usersBoardsService; public BoardPermissionHandler(IUsersBoardsService usersBoardsService) { _usersBoardsService = usersBoardsService; } protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, BoardPermissionRequirement requirement, BoardRequest resource) { if(context.User == null || resource == null) { return; } Claim nameIdentifierClaim = context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier); string userId = nameIdentifierClaim?.Value; OutBoardPermission permission = await _usersBoardsService.GetPermissionAsync(userId, resource.BoardId); if(permission != 0 && permission >= requirement.Permission) { context.Succeed(requirement); } } } }
mit
C#
d1f874edee63e051793159b23fa7a0dcec537311
Move using directives inside namespace for ElmahController class.
fhchina/elmah-mvc,mmsaffari/elmah-mvc,jmptrader/elmah-mvc,alexbeletsky/elmah-mvc
src/Elmah.Mvc/ElmahController.cs
src/Elmah.Mvc/ElmahController.cs
// // ELMAH.Mvc // Copyright (c) 2011 Atif Aziz, James Driscoll. All rights reserved. // // Author(s): // // James Driscoll // // 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 Elmah.Mvc { using System.Web.Mvc; [Authorize] public class ElmahController : Controller { public ActionResult Index(string resource) { /* Adapted by Alexander Beletsky */ return new ElmahResult(); } public ActionResult Detail(string resource) { /* Adapted by Alexander Beletsky */ return new ElmahResult(); } } }
// // ELMAH.Mvc // Copyright (c) 2011 Atif Aziz, James Driscoll. All rights reserved. // // Author(s): // // James Driscoll // // 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.Web.Mvc; namespace Elmah.Mvc { [Authorize] public class ElmahController : Controller { public ActionResult Index(string resource) { /* Adapted by Alexander Beletsky */ return new ElmahResult(); } public ActionResult Detail(string resource) { /* Adapted by Alexander Beletsky */ return new ElmahResult(); } } }
apache-2.0
C#
cfbbe4247f133d13270fc088fcfee4c2f9406935
Fix #26
schulz3000/deepstreamNet,schulz3000/deepstreamNet
src/DeepStreamNet/Records/DeepStreamRecordBaseOfT.cs
src/DeepStreamNet/Records/DeepStreamRecordBaseOfT.cs
using System.ComponentModel; using Newtonsoft.Json.Linq; using System; namespace DeepStreamNet { class DeepStreamRecordBase<T> : DeepStreamRecordBase, IDeepStreamRecordWrapper, IDisposable where T : JContainer { static readonly JsonMergeSettings jsonMergeSettings = new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace, MergeNullValueHandling = MergeNullValueHandling.Merge }; protected JsonNetChangeListener Listener; public override dynamic this[object key] { get => Data[key]; set => Data[key] = value; } protected T Data; public override event PropertyChangedEventHandler PropertyChanged { add { Listener.PropertyChanged += value; } remove { Listener.PropertyChanged -= value; } } protected DeepStreamRecordBase(string name, int version, T data) : base(name, version) { Data = data; Data.AddAnnotation(name); Listener = JsonNetChangeListener.Create(Data); } public void Patch(string path, JToken item) { if (path.EndsWith("]", StringComparison.Ordinal) && Data.SelectToken(path) == null) { var arrayParentPath = path.Substring(0, path.Length - (path.LastIndexOf("[", StringComparison.Ordinal) + 1)); var token = Data.SelectToken(arrayParentPath); ((JArray)token).Add(item); } else { Data.SelectToken(path)?.Replace(item); } } public void Update(JToken item) { Data.Merge(item, jsonMergeSettings); Data.AddAnnotation(RecordName); } public object Get(string path) => Data.SelectToken(path); public override string ToString() => Data.ToString(); public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool disposing) { if (disposing) { Listener.Dispose(); } } } }
using System.ComponentModel; using Newtonsoft.Json.Linq; using System; namespace DeepStreamNet { class DeepStreamRecordBase<T> : DeepStreamRecordBase, IDeepStreamRecordWrapper, IDisposable where T : JContainer { protected JsonNetChangeListener Listener; public override dynamic this[object key] { get => Data[key]; set => Data[key] = value; } protected T Data; public override event PropertyChangedEventHandler PropertyChanged { add { Listener.PropertyChanged += value; } remove { Listener.PropertyChanged -= value; } } protected DeepStreamRecordBase(string name, int version, T data) : base(name, version) { Data = data; Data.AddAnnotation(name); Listener = JsonNetChangeListener.Create(Data); } public void Patch(string path, JToken item) { if (path.EndsWith("]", StringComparison.Ordinal) && Data.SelectToken(path) == null) { var arrayParentPath = path.Substring(0, path.Length - (path.LastIndexOf("[", StringComparison.Ordinal)+1)); var token = Data.SelectToken(arrayParentPath); ((JArray)token).Add(item); } else { Data.SelectToken(path)?.Replace(item); } } public void Update(JToken item) { Data = (T)item; Data.AddAnnotation(RecordName); //Listener.Resubscribe(Data); } public object Get(string path) => Data.SelectToken(path); public override string ToString() => Data.ToString(); public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool disposing) { if (disposing) { Listener.Dispose(); } } } }
mit
C#
1f1294d46518728e903a5f23e59eebd9fc35d3af
优化代码。
tangxuehua/enode,Aaron-Liu/enode
src/ENode/Commanding/Impl/DefaultCommandProcessor.cs
src/ENode/Commanding/Impl/DefaultCommandProcessor.cs
using System.Collections.Concurrent; using ECommon.Logging; namespace ENode.Commanding.Impl { public class DefaultCommandProcessor : ICommandProcessor { private readonly ConcurrentDictionary<string, CommandMailbox> _mailboxDict; private readonly ICommandScheduler _commandScheduler; private readonly ICommandExecutor _commandExecutor; private readonly ILoggerFactory _loggerFactory; public DefaultCommandProcessor(ICommandScheduler commandScheduler, ICommandExecutor commandExecutor, ILoggerFactory loggerFactory) { _mailboxDict = new ConcurrentDictionary<string, CommandMailbox>(); _commandScheduler = commandScheduler; _commandExecutor = commandExecutor; _loggerFactory = loggerFactory; } public void Process(ProcessingCommand processingCommand) { if (string.IsNullOrEmpty(processingCommand.AggregateRootId)) { _commandScheduler.ScheduleCommand(processingCommand); } else { var commandMailbox = _mailboxDict.GetOrAdd(processingCommand.AggregateRootId, key => new CommandMailbox(_commandScheduler, _commandExecutor, _loggerFactory)); commandMailbox.EnqueueCommand(processingCommand); _commandScheduler.ScheduleCommandMailbox(commandMailbox); } } } }
using System.Collections.Concurrent; using ECommon.Logging; namespace ENode.Commanding.Impl { public class DefaultCommandProcessor : ICommandProcessor { private readonly ConcurrentDictionary<string, CommandMailbox> _mailboxDict; private readonly ICommandScheduler _commandScheduler; private readonly ICommandExecutor _commandExecutor; private readonly ILoggerFactory _loggerFactory; public DefaultCommandProcessor(ICommandScheduler commandScheduler, ICommandExecutor commandExecutor, ILoggerFactory loggerFactory) { _mailboxDict = new ConcurrentDictionary<string, CommandMailbox>(); _commandScheduler = commandScheduler; _commandExecutor = commandExecutor; _loggerFactory = loggerFactory; } public void Process(ProcessingCommand processingCommand) { if (string.IsNullOrEmpty(processingCommand.AggregateRootId)) { _commandScheduler.ScheduleCommand(processingCommand); } else { var commandMailbox = _mailboxDict.GetOrAdd(processingCommand.AggregateRootId, new CommandMailbox(_commandScheduler, _commandExecutor, _loggerFactory)); commandMailbox.EnqueueCommand(processingCommand); _commandScheduler.ScheduleCommandMailbox(commandMailbox); } } } }
mit
C#
bfad86dcdec532e18e076e2ad7bfc89c9f7d24d3
Fix indenting. Comment on intermittent failures.
hazzik/nhibernate-core,ManufacturingIntelligence/nhibernate-core,ngbrown/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,alobakov/nhibernate-core,fredericDelaporte/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nkreipke/nhibernate-core,nkreipke/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,ngbrown/nhibernate-core,alobakov/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core,hazzik/nhibernate-core,alobakov/nhibernate-core,fredericDelaporte/nhibernate-core,ngbrown/nhibernate-core,lnu/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,lnu/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,RogerKratz/nhibernate-core,lnu/nhibernate-core,livioc/nhibernate-core,nhibernate/nhibernate-core,nkreipke/nhibernate-core,gliljas/nhibernate-core,livioc/nhibernate-core
src/NHibernate.Test/NHSpecificTest/NH2057/Fixture.cs
src/NHibernate.Test/NHSpecificTest/NH2057/Fixture.cs
using System; using System.Collections.Generic; using System.Data; using System.Transactions; using NHibernate.Impl; using NUnit.Framework; using NHibernate.Criterion; namespace NHibernate.Test.NHSpecificTest.NH2057 { [TestFixture] public class Fixture : BugTestCase { [Test] [Description("This test fails intermittently on SQL Server ODBC. Not sure why.")] public void WillCloseWhenUsingDTC() { SessionImpl s; using (var tx = new TransactionScope()) { using (s = (SessionImpl)OpenSession()) { s.Get<Person>(1); } //not closed because the tx is opened yet Assert.False(s.IsClosed); tx.Complete(); } Assert.True(s.IsClosed); } } }
using System; using System.Collections.Generic; using System.Data; using System.Transactions; using NHibernate.Impl; using NUnit.Framework; using NHibernate.Criterion; namespace NHibernate.Test.NHSpecificTest.NH2057 { [TestFixture] public class Fixture : BugTestCase { [Test] public void WillCloseWhenUsingDTC() { SessionImpl s; using (var tx = new TransactionScope()) { using (s = (SessionImpl)OpenSession()) { s.Get<Person>(1); } //not closed because the tx is opened yet Assert.False(s.IsClosed); tx.Complete(); } Assert.True(s.IsClosed); } } }
lgpl-2.1
C#
32d04a73b74e10237212beba043c011e995844de
Remove unnecessary Dialect restriction from NH3070 testcase
ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,livioc/nhibernate-core,nkreipke/nhibernate-core,gliljas/nhibernate-core,nkreipke/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,ngbrown/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,ManufacturingIntelligence/nhibernate-core,lnu/nhibernate-core,hazzik/nhibernate-core,lnu/nhibernate-core,lnu/nhibernate-core,nhibernate/nhibernate-core,ManufacturingIntelligence/nhibernate-core,RogerKratz/nhibernate-core,alobakov/nhibernate-core,nkreipke/nhibernate-core,alobakov/nhibernate-core,alobakov/nhibernate-core,ngbrown/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core
src/NHibernate.Test/NHSpecificTest/NH3070/Fixture.cs
src/NHibernate.Test/NHSpecificTest/NH3070/Fixture.cs
using NHibernate.Mapping.ByCode; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH3070 { [TestFixture] public class Fixture : TestCaseMappingByCode { protected override Cfg.MappingSchema.HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.Class<Employee>(ca => { ca.Id(x => x.Id, map => { map.Column("Id"); map.Generator(Generators.Identity); }); ca.Property(x => x.FirstName, map => { map.Formula("(select 'something')"); map.Lazy(true); }); }); return mapper.CompileMappingForAllExplicitlyAddedEntities(); } [Test, Ignore("Not fixed yet.")] public void ProxyForEntityWithLazyPropertiesAndFormulaShouldEqualItself() { try { using (var s = OpenSession()) using (var t = s.BeginTransaction()) { var emp = new Employee(); s.Save(emp); t.Commit(); } using (var session = OpenSession()) { var emps = session.QueryOver<Employee>().List(); var emp = emps[0]; // THIS ASSERT WILL FAIL Assert.IsTrue(emp.Equals(emp), "Equals"); } } finally { using (var s = OpenSession()) using (var t = s.BeginTransaction()) { s.Delete("from Employee"); t.Commit(); } } } } public class Employee { public virtual int Id { get; protected set; } public virtual string FirstName { get; set; } } }
using System; using NHibernate.Mapping.ByCode; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH3070 { [TestFixture] public class Fixture : TestCaseMappingByCode { protected override bool AppliesTo(Dialect.Dialect dialect) { return dialect is Dialect.MsSql2005Dialect; } protected override Cfg.MappingSchema.HbmMapping GetMappings() { var mapper = new ModelMapper(); mapper.Class<Employee>(ca => { ca.Id(x => x.Id, map => { map.Column("Id"); map.Generator(Generators.Identity); }); ca.Property(x => x.FirstName, map => { map.Formula("(select 'something')"); map.Lazy(true); }); }); return mapper.CompileMappingForAllExplicitlyAddedEntities(); } [Test, Ignore("Not fixed yet.")] public void ProxyForEntityWithLazyPropertiesAndFormulaShouldEqualItself() { try { using (var s = OpenSession()) using (var t = s.BeginTransaction()) { var emp = new Employee(); s.Save(emp); t.Commit(); } using (var session = OpenSession()) { var emps = session.QueryOver<Employee>().List(); var emp = emps[0]; // THIS ASSERT WILL FAIL Assert.IsTrue(emp.Equals(emp), "Equals"); } } finally { using (var s = OpenSession()) using (var t = s.BeginTransaction()) { s.Delete("from Employee"); t.Commit(); } } } } public class Employee { public virtual int Id { get; protected set; } public virtual string FirstName { get; set; } } }
lgpl-2.1
C#
73789bf6fffb59ea16796ae5a932df68de4d28fe
Improve samples
Kinnara/KinnaraToolkit
KinnaraToolkitSample/KinnaraToolkitSample.WPA81/Data/SampleItems.cs
KinnaraToolkitSample/KinnaraToolkitSample.WPA81/Data/SampleItems.cs
using KinnaraToolkitSample.ContextMenu; using KinnaraToolkitSample.DateTimePickers; using KinnaraToolkitSample.PageUI; using System.Collections.ObjectModel; namespace KinnaraToolkitSample.Data { public class SampleItems : ObservableCollection<SampleItem> { public SampleItems() { Add(new SampleItem("context menu", typeof(ContextMenuSample))); Add(new SampleItem("date picker", typeof(DatePickerSample))); Add(new SampleItem("page ui", typeof(PageUISample))); Add(new SampleItem("system tray", typeof(SystemTraySample))); Add(new SampleItem("time picker", typeof(TimePickerSample))); } } }
using KinnaraToolkitSample.ContextMenu; using KinnaraToolkitSample.DateTimePickers; using KinnaraToolkitSample.PageUI; using System.Collections.ObjectModel; namespace KinnaraToolkitSample.Data { public class SampleItems : ObservableCollection<SampleItem> { public SampleItems() { Add(new SampleItem("page ui", typeof(PageUISample))); Add(new SampleItem("date picker", typeof(DatePickerSample))); Add(new SampleItem("time picker", typeof(TimePickerSample))); Add(new SampleItem("context menu", typeof(ContextMenuSample))); Add(new SampleItem("system tray", typeof(SystemTraySample))); } } }
mit
C#
1d38187e0deaaf695451cd310af2319e27eca022
Patch method added.
nseckinoral/xomni-sdk-dotnet
src/XOMNI.SDK.Core/Management/BaseCRUDPManagement.cs
src/XOMNI.SDK.Core/Management/BaseCRUDPManagement.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using XOMNI.SDK.Core.ApiAccess; namespace XOMNI.SDK.Core.Management { public abstract class BaseCRUDPManagement<T> : BaseCRUDManagement<T> { protected override CRUDApiAccessBase<T> ApiAccess { get { return CRUDPApiAccess; } } protected abstract CRUDPApiAccessBase<T> CRUDPApiAccess { get; } /// <summary> /// Updates an entity /// </summary> /// <param name="entity">Dynamic entity to be updated</param> /// <returns>Updated entity</returns> public virtual Task<T> UpdateAsync(dynamic entity) { return CRUDPApiAccess.PatchAsync(entity, base.ApiCredential); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using XOMNI.SDK.Core.ApiAccess; namespace XOMNI.SDK.Core.Management { public abstract class BaseCRUDPManagement<T> : BaseCRUDManagement<T> { protected override CRUDApiAccessBase<T> ApiAccess { get { return CRUDPApiAccess; } } protected abstract CRUDPApiAccessBase<T> CRUDPApiAccess { get; } } }
mit
C#
19c92c91f0cd1fdcbe273bffcdb930f7499da0c6
revert registration of most services to transient, leaving only IFileSystemService as Singleton since it needs to hold state of the data folder override
zmira/abremir.AllMyBricks
abremir.AllMyBricks.DatabaseSeeder/Configuration/IoC.cs
abremir.AllMyBricks.DatabaseSeeder/Configuration/IoC.cs
using abremir.AllMyBricks.DatabaseSeeder.Loggers; using abremir.AllMyBricks.DatabaseSeeder.Services; using abremir.AllMyBricks.Device.Interfaces; using Easy.MessageHub; using SimpleInjector; using System.Reflection; namespace abremir.AllMyBricks.DatabaseSeeder.Configuration { public static class IoC { public static Container IoCContainer { get; private set; } public static void Configure() { IoCContainer = new Container(); DataSynchronizer.Configuration.IoC.Configure(IoCContainer); ThirdParty.Brickset.Configuration.IoC.Configure(IoCContainer); Data.Configuration.IoC.Configure(IoCContainer); AssetManagement.Configuration.IoC.Configure(IoCContainer); UserManagement.Configuration.IoC.Configure(IoCContainer); IoCContainer.Register<IPreferencesService, PreferencesService>(Lifestyle.Transient); IoCContainer.Register<ISecureStorageService, SecureStorageService>(Lifestyle.Transient); IoCContainer.Register<IDeviceInformationService, DeviceInformationService>(Lifestyle.Transient); IoCContainer.Register<IAssetManagementService, AssetManagementService>(Lifestyle.Transient); IoCContainer.Register<IFileSystemService, FileSystemService>(Lifestyle.Singleton); IoCContainer.Register<IMessageHub, MessageHub>(Lifestyle.Singleton); IoCContainer.Register(() => Logging.Factory, Lifestyle.Singleton); IoCContainer.Collection.Register<IDatabaseSeederLogger>(Assembly.GetExecutingAssembly()); Onboarding.Configuration.FlurlConfiguration.Configure(); } public static void ConfigureOnboarding(string allMyBricksOnboardingUrl) { Onboarding.Configuration.IoC.Configure(allMyBricksOnboardingUrl, IoCContainer); } public static void ReplaceOnboarding(string allMyBricksOnboardingUrl) { IoCContainer.Options.AllowOverridingRegistrations = true; ConfigureOnboarding(allMyBricksOnboardingUrl); IoCContainer.Options.AllowOverridingRegistrations = false; } } }
using abremir.AllMyBricks.DatabaseSeeder.Loggers; using abremir.AllMyBricks.DatabaseSeeder.Services; using abremir.AllMyBricks.Device.Interfaces; using Easy.MessageHub; using SimpleInjector; using System.Reflection; namespace abremir.AllMyBricks.DatabaseSeeder.Configuration { public static class IoC { public static Container IoCContainer { get; private set; } public static void Configure() { IoCContainer = new Container(); DataSynchronizer.Configuration.IoC.Configure(IoCContainer); ThirdParty.Brickset.Configuration.IoC.Configure(IoCContainer); Data.Configuration.IoC.Configure(IoCContainer); AssetManagement.Configuration.IoC.Configure(IoCContainer); UserManagement.Configuration.IoC.Configure(IoCContainer); IoCContainer.Register<IPreferencesService, PreferencesService>(Lifestyle.Singleton); IoCContainer.Register<ISecureStorageService, SecureStorageService>(Lifestyle.Singleton); IoCContainer.Register<IDeviceInformationService, DeviceInformationService>(Lifestyle.Singleton); IoCContainer.Register<IFileSystemService, FileSystemService>(Lifestyle.Singleton); IoCContainer.Register<IAssetManagementService, AssetManagementService>(Lifestyle.Singleton); IoCContainer.Register<IMessageHub, MessageHub>(Lifestyle.Singleton); IoCContainer.Register(() => Logging.Factory, Lifestyle.Singleton); IoCContainer.Collection.Register<IDatabaseSeederLogger>(Assembly.GetExecutingAssembly()); Onboarding.Configuration.FlurlConfiguration.Configure(); } public static void ConfigureOnboarding(string allMyBricksOnboardingUrl) { Onboarding.Configuration.IoC.Configure(allMyBricksOnboardingUrl, IoCContainer); } public static void ReplaceOnboarding(string allMyBricksOnboardingUrl) { IoCContainer.Options.AllowOverridingRegistrations = true; ConfigureOnboarding(allMyBricksOnboardingUrl); IoCContainer.Options.AllowOverridingRegistrations = false; } } }
mit
C#
dba328016a5736e4704923b5c531ada4b3f4fac8
Move request changed for uniformity
yar229/WebDavMailRuCloud
MailRuCloud/MailRuCloudApi/Base/Requests/WebM1/MoveRequest.cs
MailRuCloud/MailRuCloudApi/Base/Requests/WebM1/MoveRequest.cs
using System; using System.Net; using System.Text; using YaR.MailRuCloud.Api.Base.Requests.Repo; namespace YaR.MailRuCloud.Api.Base.Requests.WebM1 { class MoveRequest : BaseRequestJson<WebV2.CopyRequest.Result> { private readonly string _sourceFullPath; private readonly string _destinationPath; public MoveRequest(IWebProxy proxy, IAuth auth, string sourceFullPath, string destinationPath) : base(proxy, auth) { _sourceFullPath = sourceFullPath; _destinationPath = destinationPath; } protected override string RelationalUri => $"/api/m1/file/move?access_token={Auth.AccessToken}"; protected override byte[] CreateHttpContent() { var data = $"home={Uri.EscapeDataString(_sourceFullPath)}&email={Auth.Login}&conflict=rename&folder={Uri.EscapeDataString(_destinationPath)}"; return Encoding.UTF8.GetBytes(data); } } }
using System; using System.Net; using System.Text; using YaR.MailRuCloud.Api.Base.Requests.Repo; namespace YaR.MailRuCloud.Api.Base.Requests.WebM1 { class MoveRequest : BaseRequestJson<WebV2.CopyRequest.Result> { private readonly string _sourceFullPath; private readonly string _destinationPath; public MoveRequest(IWebProxy proxy, IAuth auth, string sourceFullPath, string destinationPath) : base(proxy, auth) { _sourceFullPath = sourceFullPath; _destinationPath = destinationPath; } protected override string RelationalUri => $"/api/m1/file/move?access_token={Auth.AccessToken}"; protected override byte[] CreateHttpContent() { var data = Encoding.UTF8.GetBytes($"home={Uri.EscapeDataString(_sourceFullPath)}&email={Auth.Login}&conflict=rename&folder={Uri.EscapeDataString(_destinationPath)}"); return data; } } }
mit
C#
8dffb0d1f3d62796afd9e4c3ffdda8aad90b375d
Disable autocomplete for payment amount
Viincenttt/MollieApi,Viincenttt/MollieApi
Mollie.WebApplicationCoreExample/Views/Payment/Create.cshtml
Mollie.WebApplicationCoreExample/Views/Payment/Create.cshtml
@using Mollie.WebApplicationCoreExample.Framework.Extensions @model CreatePaymentModel @{ ViewData["Title"] = "Create payment"; } <div class="container"> <h2>Create new payment</h2> <form method="post"> <div asp-validation-summary="All"></div> <div class="row"> <div class="col-6"> <div class="form-group"> <label asp-for="Amount"></label> <input class="form-control" asp-for="Amount" autocomplete="off" /> </div> <div class="form-group"> <label asp-for="Currency"></label> <select class="form-control" asp-for="Currency" asp-items="@Html.GetStaticStringSelectList(typeof(Currency))"></select> </div> <div class="form-group"> <label asp-for="Description"></label> <textarea class="form-control" asp-for="Description" rows="4"></textarea> </div> <input type="submit" name="Save" value="Save" class="btn btn-primary" /> </div> </div> </form> </div>
@using Mollie.WebApplicationCoreExample.Framework.Extensions @model CreatePaymentModel @{ ViewData["Title"] = "Create payment"; } <div class="container"> <h2>Create new payment</h2> <form method="post"> <div asp-validation-summary="All"></div> <div class="row"> <div class="col-6"> <div class="form-group"> <label asp-for="Amount"></label> <input class="form-control" asp-for="Amount" /> </div> <div class="form-group"> <label asp-for="Currency"></label> <select class="form-control" asp-for="Currency" asp-items="@Html.GetStaticStringSelectList(typeof(Currency))"></select> </div> <div class="form-group"> <label asp-for="Description"></label> <textarea class="form-control" asp-for="Description" rows="4"></textarea> </div> <input type="submit" name="Save" value="Save" class="btn btn-primary" /> </div> </div> </form> </div>
mit
C#
e6fdf100c41fb5ceb23981c1e31533adbe846aa7
remove unused code
plantain-00/Bootstrap.Pagination,plantain-00/Bootstrap.Pagination
Bootstrap.Pagination.net40/Views/Shared/Pagination.cshtml
Bootstrap.Pagination.net40/Views/Shared/Pagination.cshtml
@using Bootstrap.Pagination <div style="text-align: center"> <ul class="pagination"> @{ var pagination = ViewData["pagination"] as Pagination; if (pagination.IsFirstGroup) { <li class="disabled"><span>«</span></li> } else { <li><a onclick="navigateTo(@pagination.PagesPerGroup,@(pagination.Group - 1))" href="javascript:void(0);">«</a></li> } for (var i = 0; i < pagination.CurrentPageCount; i++) { if (pagination.IsCurrentPage(i)) { <li class="active"><span>@pagination.GetPageIndex(i)</span></li> } else { <li><a onclick="navigateTo(@(i + 1),@pagination.Group);" href="javascript:void(0);">@pagination.GetPageIndex(i)</a></li> } } if (pagination.IsLastGroup) { <li class="disabled"><span>»</span></li> } else { <li><a onclick="navigateTo(1,@(pagination.Group + 1));" href="javascript:void(0);">»</a></li> } } </ul> </div>
@using Bootstrap.Pagination <div style="text-align: center"> <ul class="pagination"> @{ var pagination = ViewData["pagination"] as Pagination; var url = ViewData["url"] as string; if (pagination.IsFirstGroup) { <li class="disabled"><span>«</span></li> } else { <li><a onclick="navigateTo(@pagination.PagesPerGroup,@(pagination.Group - 1))" href="javascript:void(0);">«</a></li> } for (var i = 0; i < pagination.CurrentPageCount; i++) { if (pagination.IsCurrentPage(i)) { <li class="active"><span>@pagination.GetPageIndex(i)</span></li> } else { <li><a onclick="navigateTo(@(i + 1),@pagination.Group);" href="javascript:void(0);">@pagination.GetPageIndex(i)</a></li> } } if (pagination.IsLastGroup) { <li class="disabled"><span>»</span></li> } else { <li><a onclick="navigateTo(1,@(pagination.Group + 1));" href="javascript:void(0);">»</a></li> } } </ul> </div>
mit
C#
bbfd48c9bb87a7e5dad9398cfa2fd00b378dde57
add tint experimental
reinterpretcat/utymap,reinterpretcat/utymap,reinterpretcat/utymap
unity/demo/Assets/Scripts/Scene/Gestures/SurfaceGestureStrategy.cs
unity/demo/Assets/Scripts/Scene/Gestures/SurfaceGestureStrategy.cs
using System; using Assets.Scripts.Scene.Tiling; using TouchScript.Gestures.TransformGestures; using UnityEngine; namespace Assets.Scripts.Scene.Gestures { internal class SurfaceGestureStrategy : GestureStrategy { private const float PanMaxSpeed = 1f; private const float PanMinSpeed = 0.005f; private const float PanFactor = 0.05f; private const float ZoomMaxSpeed = 100f; private const float ZoomMinSpeed = 1f; private const float ZoomFactor = 0.5f; private const float TintMax = 0f; private const float TintMin = -22.5f; private const float TintSpeed = 0.1f; public SurfaceGestureStrategy(TileController tileController, ScreenTransformGesture twoFingerMoveGesture, ScreenTransformGesture manipulationGesture) : base(tileController, twoFingerMoveGesture, manipulationGesture) { } public override void OnManipulationTransform(Transform pivot, Transform camera) { var speed = Mathf.Max(PanMaxSpeed * InterpolateByZoom(PanFactor), PanMinSpeed); pivot.localPosition += new Vector3(ManipulationGesture.DeltaPosition.x, 0, ManipulationGesture.DeltaPosition.y) * -speed; } public override void OnTwoFingerTransform(Transform pivot, Transform camera) { if (SetTint(pivot, camera)) return; var speed = Mathf.Max(ZoomMaxSpeed * InterpolateByZoom(ZoomFactor), ZoomMinSpeed); pivot.localPosition += Vector3.up * (1 - TwoFingerMoveGesture.DeltaScale) * speed; } /// <remarks> /// Experimental. Should be replaced with custom gesture. /// </remarks> private bool SetTint(Transform pivot, Transform camera) { var pointer1 = TwoFingerMoveGesture.ActivePointers[0]; var pointer2 = TwoFingerMoveGesture.ActivePointers[1]; var delta1 = pointer1.Position - pointer1.PreviousPosition; var delta2 = pointer2.Position - pointer2.PreviousPosition; // different direction if (delta1.y < 0 != delta2.y < 0) return false; // ignore small values if (Mathf.Abs(delta1.y) < 2f || Mathf.Abs(delta2.y) < 2f) return false; // rather zoom than tint if (Mathf.Abs(delta1.x / delta1.y) > 0.5f || Mathf.Abs(delta2.x / delta2.y) > 0.5f) return false; // fingers are too far if (Mathf.Abs(delta1.y - delta2.y) > 1) return false; var angle = pivot.rotation.eulerAngles.x + (delta1.y + delta2.y) * TintSpeed / 2 - 360; pivot.rotation = Quaternion.Euler(Mathf.Clamp(angle, TintMin, TintMax), 0, 0); return true; } } }
using Assets.Scripts.Scene.Tiling; using TouchScript.Gestures.TransformGestures; using UnityEngine; namespace Assets.Scripts.Scene.Gestures { internal class SurfaceGestureStrategy : GestureStrategy { private const float PanMaxSpeed = 1f; private const float PanMinSpeed = 0.005f; private const float PanFactor = 0.05f; private const float ZoomMaxSpeed = 100f; private const float ZoomMinSpeed = 1f; private const float ZoomFactor = 0.5f; public SurfaceGestureStrategy(TileController tileController, ScreenTransformGesture twoFingerMoveGesture, ScreenTransformGesture manipulationGesture) : base(tileController, twoFingerMoveGesture, manipulationGesture) { } public override void OnManipulationTransform(Transform pivot, Transform camera) { var speed = Mathf.Max(PanMaxSpeed * InterpolateByZoom(PanFactor), PanMinSpeed); pivot.localPosition += new Vector3(ManipulationGesture.DeltaPosition.x, 0, ManipulationGesture.DeltaPosition.y) * -speed; } public override void OnTwoFingerTransform(Transform pivot, Transform camera) { var speed = Mathf.Max(ZoomMaxSpeed * InterpolateByZoom(ZoomFactor), ZoomMinSpeed); pivot.localPosition += Vector3.up * (1 - TwoFingerMoveGesture.DeltaScale) * speed; } } }
apache-2.0
C#
198e3c3617aa56f4a08b1345ca4b8c3edd09eb08
Add comments
aluxnimm/outlookcaldavsynchronizer
GenSync/Synchronization/ISynchronizationContextFactory.cs
GenSync/Synchronization/ISynchronizationContextFactory.cs
// This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/) // Copyright (c) 2015 Gerhard Zehetbauer // Copyright (c) 2015 Alexander Nimmervoll // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GenSync.Synchronization { /// <summary> /// Creates the synchronization context. /// The Synchronization context respresents user defined data and is passed through all components (e.g. repositories, entitymappers, etc...) /// </summary> /// <typeparam name="TContext"></typeparam> public interface ISynchronizationContextFactory<TContext> { /// <summary> /// Is called at the beginning of every sync run, to create an context for the ongoing sync run /// </summary> /// <returns></returns> Task<TContext> Create(); /// <summary> /// Is called at the end of every sync run with the previously created context /// </summary> /// <param name="context"></param> /// <returns></returns> Task SynchronizationFinished(TContext context); } }
// This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/) // Copyright (c) 2015 Gerhard Zehetbauer // Copyright (c) 2015 Alexander Nimmervoll // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GenSync.Synchronization { public interface ISynchronizationContextFactory<TContext> { Task<TContext> Create (); Task SynchronizationFinished (TContext context); } }
agpl-3.0
C#
cd95777829f6024c1711b69ba34bd0f3bd784b4e
Fix for allegiance update done message. (#689)
LtRipley36706/ACE,Lidefeath/ACE,ACEmulator/ACE,LtRipley36706/ACE,ACEmulator/ACE,LtRipley36706/ACE,ACEmulator/ACE
Source/ACE.Server/Network/GameEvent/Events/GameEventAllegianceAllegianceUpdateDone.cs
Source/ACE.Server/Network/GameEvent/Events/GameEventAllegianceAllegianceUpdateDone.cs
using ACE.Server.Network.GameMessages; namespace ACE.Server.Network.GameEvent.Events { public class GameEventAllegianceAllegianceUpdateDone : GameEventMessage { public GameEventAllegianceAllegianceUpdateDone(Session session) : base(GameEventType.AllegianceAllegianceUpdateDone, GameMessageGroup.UIQueue, session) { Writer.Write(0x00); } } }
using ACE.Server.Network.GameMessages; namespace ACE.Server.Network.GameEvent.Events { public class GameEventAllegianceAllegianceUpdateDone : GameMessage { public GameEventAllegianceAllegianceUpdateDone(Session session) : base(GameMessageOpcode.GameEvent, GameMessageGroup.UIQueue) { //Writer.Write(session.Player.Guid.Full); //Writer.Write(session.GameEventSequence++); //Writer.Write((uint)GameEvent.GameEventType.AllegianceAllegianceUpdateDone); Writer.Write(0x00); } } }
agpl-3.0
C#
badfa358ffef7093325f5497624d93fb8d25cd87
Enforce Tls 1.2
projectkudu/AzureResourceExplorer,projectkudu/AzureResourceExplorer,projectkudu/ARMExplorer,projectkudu/AzureResourceExplorer,projectkudu/AzureResourceExplorer,projectkudu/ARMExplorer,projectkudu/ARMExplorer,projectkudu/ARMExplorer
Global.asax.cs
Global.asax.cs
using ARMExplorer.App_Start; using System.Configuration; using System.Net; using System.Web.Http; namespace ARMExplorer { public class Global : System.Web.HttpApplication { protected void Application_Start() { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration .Active.InstrumentationKey = ConfigurationManager.AppSettings["AppInsightKey"] ?? System.Environment.GetEnvironmentVariable("AppInsightKey") ?? string.Empty; WebApiConfig.Register(GlobalConfiguration.Configuration); } } }
using ARMExplorer.App_Start; using System.Configuration; using System.Web.Http; namespace ARMExplorer { public class Global : System.Web.HttpApplication { protected void Application_Start() { Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration .Active.InstrumentationKey = ConfigurationManager.AppSettings["AppInsightKey"] ?? System.Environment.GetEnvironmentVariable("AppInsightKey") ?? string.Empty; WebApiConfig.Register(GlobalConfiguration.Configuration); } } }
apache-2.0
C#
11771cc052fb22a1982eb387763e7141519bf63b
Update UrlFormatter.cs
WasimAhmad/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,WasimAhmad/Serenity,dfaruque/Serenity,rolembergfilho/Serenity,dfaruque/Serenity,dfaruque/Serenity,WasimAhmad/Serenity,dfaruque/Serenity,dfaruque/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity
Serenity.Script.Core/SlickGrid/Formatters/UrlFormatter.cs
Serenity.Script.Core/SlickGrid/Formatters/UrlFormatter.cs
using Serenity.ComponentModel; namespace Serenity { public class UrlFormatter : ISlickFormatter { public string Format(SlickFormatterContext ctx) { var display = !string.IsNullOrEmpty(DisplayProperty) ? ctx.Item[DisplayProperty] as string : ctx.Value; var url = !string.IsNullOrEmpty(UrlProperty) ? ctx.Item[UrlProperty] as string : ctx.Value; return "<a href='" + Q.HtmlEncode(url) + "'>" + Q.HtmlEncode(display) + "</a>"; } [Option] public string DisplayProperty { get; set; } [Option] public string UrlProperty { get; set; } } }
namespace Serenity { public class UrlFormatter : ISlickFormatter { public string Format(SlickFormatterContext ctx) { var display = !string.IsNullOrEmpty(DisplayProperty) ? ctx.Item[DisplayProperty] as string : ctx.Value; var url = !string.IsNullOrEmpty(UrlProperty) ? ctx.Item[UrlProperty] as string : ctx.Value; return "<a href='" + url + "'>" + display + "</a>"; } [Option] public string DisplayProperty { get; set; } [Option] public string UrlProperty { get; set; } } }
mit
C#
3198bad7212b23f7ab5d745addae3140d9424cae
allow overriding sort expressions in queryable to-many materializer
JSONAPIdotNET/JSONAPI.NET,SphtKr/JSONAPI.NET
JSONAPI/Http/QueryableToManyRelatedResourceDocumentMaterializer.cs
JSONAPI/Http/QueryableToManyRelatedResourceDocumentMaterializer.cs
using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using JSONAPI.Documents; using JSONAPI.Documents.Builders; namespace JSONAPI.Http { /// <summary> /// Base class for implementations of <see cref="IRelatedResourceDocumentMaterializer"/> that use IQueryable to get related resources /// for a to-many relationship. /// </summary> public abstract class QueryableToManyRelatedResourceDocumentMaterializer<TRelated> : IRelatedResourceDocumentMaterializer { private readonly IQueryableResourceCollectionDocumentBuilder _queryableResourceCollectionDocumentBuilder; private readonly ISortExpressionExtractor _sortExpressionExtractor; /// <summary> /// Creates a new QueryableRelatedResourceDocumentMaterializer /// </summary> protected QueryableToManyRelatedResourceDocumentMaterializer( IQueryableResourceCollectionDocumentBuilder queryableResourceCollectionDocumentBuilder, ISortExpressionExtractor sortExpressionExtractor) { _queryableResourceCollectionDocumentBuilder = queryableResourceCollectionDocumentBuilder; _sortExpressionExtractor = sortExpressionExtractor; } public async Task<IJsonApiDocument> GetRelatedResourceDocument(string primaryResourceId, HttpRequestMessage request, CancellationToken cancellationToken) { var query = await GetRelatedQuery(primaryResourceId, cancellationToken); var includes = GetIncludePaths(); var sortExpressions = _sortExpressionExtractor.ExtractSortExpressions(request); if (sortExpressions == null || sortExpressions.Length < 1) sortExpressions = GetDefaultSortExpressions(); return await _queryableResourceCollectionDocumentBuilder.BuildDocument(query, request, sortExpressions, cancellationToken, includes); // TODO: allow implementors to specify metadata } /// <summary> /// Gets the query for the related resources /// </summary> protected abstract Task<IQueryable<TRelated>> GetRelatedQuery(string primaryResourceId, CancellationToken cancellationToken); /// <summary> /// Gets a list of relationship paths to include /// </summary> /// <returns></returns> protected virtual string[] GetIncludePaths() { return null; } /// <summary> /// If the client doesn't request any sort expressions, these expressions will be used for sorting instead. /// </summary> /// <returns></returns> protected virtual string[] GetDefaultSortExpressions() { return null; } } }
using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using JSONAPI.Documents; using JSONAPI.Documents.Builders; namespace JSONAPI.Http { /// <summary> /// Base class for implementations of <see cref="IRelatedResourceDocumentMaterializer"/> that use IQueryable to get related resources /// for a to-many relationship. /// </summary> public abstract class QueryableToManyRelatedResourceDocumentMaterializer<TRelated> : IRelatedResourceDocumentMaterializer { private readonly IQueryableResourceCollectionDocumentBuilder _queryableResourceCollectionDocumentBuilder; private readonly ISortExpressionExtractor _sortExpressionExtractor; /// <summary> /// Creates a new QueryableRelatedResourceDocumentMaterializer /// </summary> protected QueryableToManyRelatedResourceDocumentMaterializer( IQueryableResourceCollectionDocumentBuilder queryableResourceCollectionDocumentBuilder, ISortExpressionExtractor sortExpressionExtractor) { _queryableResourceCollectionDocumentBuilder = queryableResourceCollectionDocumentBuilder; _sortExpressionExtractor = sortExpressionExtractor; } public async Task<IJsonApiDocument> GetRelatedResourceDocument(string primaryResourceId, HttpRequestMessage request, CancellationToken cancellationToken) { var query = await GetRelatedQuery(primaryResourceId, cancellationToken); var includes = GetIncludePaths(); var sortExpressions = _sortExpressionExtractor.ExtractSortExpressions(request); return await _queryableResourceCollectionDocumentBuilder.BuildDocument(query, request, sortExpressions, cancellationToken, includes); // TODO: allow implementors to specify metadata } /// <summary> /// Gets the query for the related resources /// </summary> protected abstract Task<IQueryable<TRelated>> GetRelatedQuery(string primaryResourceId, CancellationToken cancellationToken); /// <summary> /// Gets a list of relationship paths to include /// </summary> /// <returns></returns> protected virtual string[] GetIncludePaths() { return null; } } }
mit
C#
74bf889d14316b86814099e1b65933e29a359aab
Update IExchangeRateRepository.cs
tiksn/TIKSN-Framework
TIKSN.Core/Finance/ForeignExchange/Data/IExchangeRateRepository.cs
TIKSN.Core/Finance/ForeignExchange/Data/IExchangeRateRepository.cs
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using TIKSN.Data; namespace TIKSN.Finance.ForeignExchange.Data { public interface IExchangeRateRepository : IQueryRepository<ExchangeRateEntity, Guid>, IRepository<ExchangeRateEntity> { Task<IReadOnlyCollection<ExchangeRateEntity>> SearchAsync( Guid foreignExchangeID, string baseCurrencyCode, string counterCurrencyCode, DateTime dateFrom, DateTime dateTo, CancellationToken cancellationToken); } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using TIKSN.Data; namespace TIKSN.Finance.ForeignExchange.Data { public interface IExchangeRateRepository : IQueryRepository<ExchangeRateEntity, Guid>, IRepository<ExchangeRateEntity> { Task<IReadOnlyCollection<ExchangeRateEntity>> SearchAsync( Guid foreignExchangeID, string baseCurrencyCode, string counterCurrencyCode, DateTimeOffset dateFrom, DateTimeOffset dateTo, CancellationToken cancellationToken); } }
mit
C#
dced08fcd831c4ff124debfdcfd08639fd45e6ab
Test for multiple games
TheEadie/PlayerRank,TheEadie/PlayerRank
UnitTests/LeagueTests.cs
UnitTests/LeagueTests.cs
using System.Linq; using Xunit; namespace ELORank.UnitTests { public class LeagueTests { [Fact] public void CanAddPlayerToLeague() { var league = new League(new SimpleScoringStrategy()); league.AddPlayer("Foo"); Assert.Contains("Foo", league.GetLeaderBoard().Select(x => x.Name)); } [Fact] public void CanRecordSimpleGame() { var league = new League(new SimpleScoringStrategy()); league.AddPlayer("Foo"); league.AddPlayer("Bar"); var game = new Game(); game.AddResult("Foo", 5); game.AddResult("Bar", 1); league.RecordGame(game); Assert.Equal(5.0, league.GetLeaderBoard().Where(x => x.Name == "Foo").Select(x => x.Score).Single()); Assert.Equal(1.0, league.GetLeaderBoard().Where(x => x.Name == "Bar").Select(x => x.Score).Single()); } [Fact] public void CanRecordMultipleSimpleGame() { var league = new League(new SimpleScoringStrategy()); league.AddPlayer("Foo"); league.AddPlayer("Bar"); var game = new Game(); game.AddResult("Foo", 5); game.AddResult("Bar", 1); var game2 = new Game(); game2.AddResult("Foo", 3); game2.AddResult("Bar", 2); league.RecordGame(game); league.RecordGame(game2); Assert.Equal(8.0, league.GetLeaderBoard().Where(x => x.Name == "Foo").Select(x => x.Score).Single()); Assert.Equal(3.0, league.GetLeaderBoard().Where(x => x.Name == "Bar").Select(x => x.Score).Single()); } } }
using System.Linq; using System.Linq.Expressions; using Xunit; namespace ELORank.UnitTests { public class LeagueTests { [Fact] public void CanAddPlayerToLeague() { var league = new League(new SimpleScoringStrategy()); league.AddPlayer("Foo"); Assert.Contains("Foo", league.GetLeaderBoard().Select(x => x.Name)); } [Fact] public void CanRecordSimpleGame() { var league = new League(new SimpleScoringStrategy()); league.AddPlayer("Foo"); league.AddPlayer("Bar"); var game = new Game(); game.AddResult("Foo", 5); game.AddResult("Bar", 1); league.RecordGame(game); Assert.Equal(5.0, league.GetLeaderBoard().Where(x => x.Name == "Foo").Select(x => x.Score).Single()); Assert.Equal(1.0, league.GetLeaderBoard().Where(x => x.Name == "Bar").Select(x => x.Score).Single()); } } }
mit
C#
f0b9bf35cd3a46a0dc04be7ef8e52687c094607a
Declare the nullability of parsed command line arguments.
fixie/fixie
src/Fixie.Console/Options.cs
src/Fixie.Console/Options.cs
namespace Fixie.Console { public class Options { public Options( string? configuration, bool noBuild, string? framework, string? report) { Configuration = configuration ?? "Debug"; NoBuild = noBuild; Framework = framework; Report = report; } public string Configuration { get; } public bool NoBuild { get; } public bool ShouldBuild => !NoBuild; public string? Framework { get; } public string? Report { get; } } }
namespace Fixie.Console { public class Options { public Options( string configuration, bool noBuild, string framework, string report) { Configuration = configuration ?? "Debug"; NoBuild = noBuild; Framework = framework; Report = report; } public string Configuration { get; } public bool NoBuild { get; } public bool ShouldBuild => !NoBuild; public string Framework { get; } public string Report { get; } } }
mit
C#
ac48ff87da15d10a020a3cff56f8b7cdb176defe
Fix and re-enable the canvas mock.
aparajit-pratap/helix-toolkit,DynamoDS/helix-toolkit,smischke/helix-toolkit,helix-toolkit/helix-toolkit,Iluvatar82/helix-toolkit,jotschgl/helix-toolkit,0x53A/helix-toolkit,holance/helix-toolkit,huoxudong125/helix-toolkit,JeremyAnsel/helix-toolkit,CobraCalle/helix-toolkit,chrkon/helix-toolkit
Source/HelixToolkit.Wpf.SharpDX.Tests/Controls/CanvasMock.cs
Source/HelixToolkit.Wpf.SharpDX.Tests/Controls/CanvasMock.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CanvasMock.cs" company="Helix Toolkit"> // Copyright (c) 2014 Helix Toolkit contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using SharpDX; using SharpDX.Direct3D11; namespace HelixToolkit.Wpf.SharpDX.Tests.Controls { class CanvasMock : IRenderHost { public CanvasMock() { Device = EffectsManager.Device; RenderTechnique = Techniques.RenderPhong; } public Device Device { get; private set; } public Color4 ClearColor { get; private set; } public bool IsShadowMapEnabled { get; private set; } public bool IsMSAAEnabled { get; private set; } public IRenderer Renderable { get; private set; } public RenderTechnique RenderTechnique { get; private set; } public double ActualHeight { get; private set; } public double ActualWidth { get; private set; } public void SetDefaultRenderTargets() { throw new NotImplementedException(); } public void SetDefaultColorTargets(DepthStencilView dsv) { throw new NotImplementedException(); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CanvasMock.cs" company="Helix Toolkit"> // Copyright (c) 2014 Helix Toolkit contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using SharpDX; using SharpDX.Direct3D11; namespace HelixToolkit.Wpf.SharpDX.Tests.Controls { class CanvasMock : IRenderHost { public CanvasMock() { Device = EffectsManager.Device; RenderTechnique = Techniques.RenderPhong; } public Device Device { get; private set; } Color4 IRenderHost.ClearColor { get; } Device IRenderHost.Device { get; } public Color4 ClearColor { get; private set; } public bool IsShadowMapEnabled { get; private set; } public bool IsMSAAEnabled { get; private set; } public IRenderer Renderable { get; private set; } public void SetDefaultRenderTargets() { throw new NotImplementedException(); } public void SetDefaultColorTargets(DepthStencilView dsv) { throw new NotImplementedException(); } public RenderTechnique RenderTechnique { get; private set; } public double ActualHeight { get; private set; } public double ActualWidth { get; private set; } } }
mit
C#
d752f4035b6ca6c61389617bd4f2a346f6293675
Improve tests after fixing settings
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
resharper/resharper-unity/test/src/CSharp/Feature/Services/Descriptions/IdentifierTooltipTest.cs
resharper/resharper-unity/test/src/CSharp/Feature/Services/Descriptions/IdentifierTooltipTest.cs
using JetBrains.ReSharper.FeaturesTestFramework.Daemon; using JetBrains.ReSharper.Plugins.Unity.Settings; using JetBrains.ReSharper.TestFramework; using NUnit.Framework; namespace JetBrains.ReSharper.Plugins.Unity.Tests.CSharp.Feature.Services.Descriptions { [TestUnity] // The tests include tooltips from all highlighters at the caret position, which will include gutter icons for // ReSharper, but not Rider as we prefer Code Vision. Force gutter icons on to avoid splitting the test per product. [TestSetting(typeof(UnitySettings), nameof(UnitySettings.GutterIconMode), GutterIconMode.Always)] public class IdentifierTooltipTest : IdentifierTooltipTestBase { protected override string RelativeTestDataPath => @"CSharp\Daemon\IdentifierTooltip"; // TODO: ReSharper currently ignores this setting, and always shows gutter icons #if RIDER [Test, TestSetting(typeof(UnitySettings), nameof(UnitySettings.GutterIconMode), GutterIconMode.None)] public void EventFunction01() { DoNamedTest(); } [Test, TestSetting(typeof(UnitySettings), nameof(UnitySettings.GutterIconMode), GutterIconMode.None)] public void EventFunction02() { DoNamedTest(); } #endif [Test] public void EventFunctionWithGutterIcon01() { DoNamedTest(); } [Test] public void EventFunctionWithGutterIcon02() { DoNamedTest(); } [Test] public void EventFunctionParameter01() { DoNamedTest(); } [Test] public void EventFunctionParameter02() { DoNamedTest(); } } }
using JetBrains.ReSharper.FeaturesTestFramework.Daemon; using JetBrains.ReSharper.Plugins.Unity.Settings; using JetBrains.ReSharper.TestFramework; using NUnit.Framework; namespace JetBrains.ReSharper.Plugins.Unity.Tests.CSharp.Feature.Services.Descriptions { // TODO: WHY DOES TESTSETTING NOT WORK!??! [TestUnity] // The tests include tooltips from all highlighters at the caret position, which will include gutter icons for // ReSharper, but not Rider as we prefer Code Vision. Force gutter icons on to avoid splitting the test per product. // TODO: Include tests for this setting always on, and always off // ReSharper currently ignores this option, and I can't get [TestSetting] to work correctly... // [TestSetting(typeof(UnitySettings), nameof(UnitySettings.GutterIconMode), GutterIconMode.Always)] public class IdentifierTooltipTest : IdentifierTooltipTestBase { protected override string RelativeTestDataPath => @"CSharp\Daemon\IdentifierTooltip"; // TODO: TestSetting is ignored if set again. It's called, but the component doesn't see the changed value // [Test, TestSetting(typeof(UnitySettings), nameof(UnitySettings.GutterIconMode), GutterIconMode.None)] // public void EventFunction01() { DoNamedTest(); } // [Test, TestSetting(typeof(UnitySettings), nameof(UnitySettings.GutterIconMode), GutterIconMode.None)] // public void EventFunction02() { DoNamedTest(); } #if RIDER [Test] public void EventFunction01() { DoNamedTest(); } [Test] public void EventFunction02() { DoNamedTest(); } #else [Test] public void EventFunctionWithGutterIcon01() { DoNamedTest(); } [Test] public void EventFunctionWithGutterIcon02() { DoNamedTest(); } #endif [Test] public void EventFunctionParameter01() { DoNamedTest(); } [Test] public void EventFunctionParameter02() { DoNamedTest(); } } }
apache-2.0
C#
4ceb9bff5273597fea5723426a03c09ba909fbf5
Make sure GPU accel. in web view is disabled even if default cefsharp settings change
JosefNemec/Playnite,JosefNemec/Playnite,JosefNemec/Playnite
source/Playnite/CefTools.cs
source/Playnite/CefTools.cs
using CefSharp; using CefSharp.Wpf; using Playnite.Common; using Playnite.Settings; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Playnite { public class CefTools { public static bool IsInitialized { get; private set; } public static void ConfigureCef() { FileSystem.CreateDirectory(PlaynitePaths.BrowserCachePath); var settings = new CefSettings(); settings.WindowlessRenderingEnabled = true; if (settings.CefCommandLineArgs.ContainsKey("disable-gpu")) { settings.CefCommandLineArgs.Remove("disable-gpu"); } if (settings.CefCommandLineArgs.ContainsKey("disable-gpu-compositing")) { settings.CefCommandLineArgs.Remove("disable-gpu-compositing"); } settings.CefCommandLineArgs.Add("disable-gpu", "1"); settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1"); settings.CachePath = PlaynitePaths.BrowserCachePath; settings.PersistSessionCookies = true; settings.LogFile = Path.Combine(PlaynitePaths.ConfigRootPath, "cef.log"); IsInitialized = Cef.Initialize(settings); } public static void Shutdown() { Cef.Shutdown(); IsInitialized = false; } } }
using CefSharp; using CefSharp.Wpf; using Playnite.Common; using Playnite.Settings; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Playnite { public class CefTools { public static bool IsInitialized { get; private set; } public static void ConfigureCef() { FileSystem.CreateDirectory(PlaynitePaths.BrowserCachePath); var settings = new CefSettings(); settings.WindowlessRenderingEnabled = true; if (!settings.CefCommandLineArgs.ContainsKey("disable-gpu")) { settings.CefCommandLineArgs.Add("disable-gpu", "1"); } if (!settings.CefCommandLineArgs.ContainsKey("disable-gpu-compositing")) { settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1"); } settings.CachePath = PlaynitePaths.BrowserCachePath; settings.PersistSessionCookies = true; settings.LogFile = Path.Combine(PlaynitePaths.ConfigRootPath, "cef.log"); IsInitialized = Cef.Initialize(settings); } public static void Shutdown() { Cef.Shutdown(); IsInitialized = false; } } }
mit
C#
dcc1b45e29456c5a82596347c0f0b484a29be4ff
use skia for rendering on windows.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/Program.cs
WalletWasabi.Gui/Program.cs
using Avalonia; using AvalonStudio.Shell; using AvalonStudio.Shell.Extensibility.Platforms; using NBitcoin; using System; using System.IO; using System.Runtime.InteropServices; using System.Threading.Tasks; using WalletWasabi.Gui.ViewModels; using WalletWasabi.Logging; namespace WalletWasabi.Gui { internal class Program { #pragma warning disable IDE1006 // Naming Styles private static async Task Main(string[] args) #pragma warning restore IDE1006 // Naming Styles { Logger.InitializeDefaults(Path.Combine(Global.DataDir, "Logs.txt")); StatusBarViewModel statusBar = null; try { Platform.BaseDirectory = Path.Combine(Global.DataDir, "Gui"); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; BuildAvaloniaApp() .BeforeStarting(async builder => { MainWindowViewModel.Instance = new MainWindowViewModel(); var configFilePath = Path.Combine(Global.DataDir, "Config.json"); var config = new Config(configFilePath); await config.LoadOrCreateDefaultFileAsync(); Logger.LogInfo<Config>("Config is successfully initialized."); Global.InitializeConfig(config); Global.InitializeNoWallet(); statusBar = new StatusBarViewModel(Global.Nodes.ConnectedNodes, Global.Synchronizer, Global.UpdateChecker); MainWindowViewModel.Instance.StatusBar = statusBar; if (Global.Synchronizer.Network != Network.Main) { MainWindowViewModel.Instance.Title += $" - {Global.Synchronizer.Network}"; } }).StartShellApp<AppBuilder, MainWindow>("Wasabi Wallet", null, () => MainWindowViewModel.Instance); } catch (Exception ex) { Logger.LogCritical<Program>(ex); throw; } finally { MainWindowViewModel.Instance?.Dispose(); statusBar?.Dispose(); await Global.DisposeAsync(); AppDomain.CurrentDomain.UnhandledException -= CurrentDomain_UnhandledException; TaskScheduler.UnobservedTaskException -= TaskScheduler_UnobservedTaskException; } } private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) { Logger.LogWarning(e?.Exception, "UnobservedTaskException"); } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Logger.LogWarning(e?.ExceptionObject as Exception, "UnhandledException"); } private static AppBuilder BuildAvaloniaApp() { var result = AppBuilder.Configure<App>(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { result .UseWin32(true, true) .UseSkia(); } else { result.UsePlatformDetect(); } return result; } } }
using Avalonia; using AvalonStudio.Shell; using AvalonStudio.Shell.Extensibility.Platforms; using NBitcoin; using System; using System.IO; using System.Runtime.InteropServices; using System.Threading.Tasks; using WalletWasabi.Gui.ViewModels; using WalletWasabi.Logging; namespace WalletWasabi.Gui { internal class Program { #pragma warning disable IDE1006 // Naming Styles private static async Task Main(string[] args) #pragma warning restore IDE1006 // Naming Styles { Logger.InitializeDefaults(Path.Combine(Global.DataDir, "Logs.txt")); StatusBarViewModel statusBar = null; try { Platform.BaseDirectory = Path.Combine(Global.DataDir, "Gui"); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; BuildAvaloniaApp() .BeforeStarting(async builder => { MainWindowViewModel.Instance = new MainWindowViewModel(); var configFilePath = Path.Combine(Global.DataDir, "Config.json"); var config = new Config(configFilePath); await config.LoadOrCreateDefaultFileAsync(); Logger.LogInfo<Config>("Config is successfully initialized."); Global.InitializeConfig(config); Global.InitializeNoWallet(); statusBar = new StatusBarViewModel(Global.Nodes.ConnectedNodes, Global.Synchronizer, Global.UpdateChecker); MainWindowViewModel.Instance.StatusBar = statusBar; if (Global.Synchronizer.Network != Network.Main) { MainWindowViewModel.Instance.Title += $" - {Global.Synchronizer.Network}"; } }).StartShellApp<AppBuilder, MainWindow>("Wasabi Wallet", null, () => MainWindowViewModel.Instance); } catch (Exception ex) { Logger.LogCritical<Program>(ex); throw; } finally { MainWindowViewModel.Instance?.Dispose(); statusBar?.Dispose(); await Global.DisposeAsync(); AppDomain.CurrentDomain.UnhandledException -= CurrentDomain_UnhandledException; TaskScheduler.UnobservedTaskException -= TaskScheduler_UnobservedTaskException; } } private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e) { Logger.LogWarning(e?.Exception, "UnobservedTaskException"); } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Logger.LogWarning(e?.ExceptionObject as Exception, "UnhandledException"); } private static AppBuilder BuildAvaloniaApp() { var result = AppBuilder.Configure<App>(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { result .UseWin32() .UseDirect2D1(); } else { result.UsePlatformDetect(); } return result; } } }
mit
C#
f6ccc4ba6881ef9bd34d6201abf23f0b9af64fe8
Update the version to 1.2.2
RachelTucker/ds3_net_sdk,rpmoore/ds3_net_sdk,rpmoore/ds3_net_sdk,SpectraLogic/ds3_net_sdk,shabtaisharon/ds3_net_sdk,SpectraLogic/ds3_net_sdk,RachelTucker/ds3_net_sdk,shabtaisharon/ds3_net_sdk,RachelTucker/ds3_net_sdk,shabtaisharon/ds3_net_sdk,SpectraLogic/ds3_net_sdk,rpmoore/ds3_net_sdk
VersionInfo.cs
VersionInfo.cs
/* * ****************************************************************************** * Copyright 2014 Spectra Logic Corporation. 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://www.apache.org/licenses/LICENSE-2.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. * **************************************************************************** */ using System.Reflection; // 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.2.2.0")] [assembly: AssemblyFileVersion("1.2.2.0")]
/* * ****************************************************************************** * Copyright 2014 Spectra Logic Corporation. 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://www.apache.org/licenses/LICENSE-2.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. * **************************************************************************** */ using System.Reflection; // 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.2.1.0")] [assembly: AssemblyFileVersion("1.2.1.0")]
apache-2.0
C#
e519db8d369df7edda52e0b01bd85ff8f2a6ec8c
Fix CIT-747 Sorting by default
ndrmc/cats,ndrmc/cats,ndrmc/cats
Web/Areas/Finance/Views/ValidatedPaymentRequest/Index.cshtml
Web/Areas/Finance/Views/ValidatedPaymentRequest/Index.cshtml
@using Cats.Areas.Procurement.Models @using Cats.Helpers @using Cats.Models @using Cats.Services.Security @using Kendo.Mvc.UI @{ ViewBag.Title = Html.Translate("Index"); Layout = "~/Views/Shared/_MainLayout.cshtml"; } <h3>Transporters having active order</h3> @(Html.Kendo().Grid<TransporterViewModel>() .Name("grid") .Columns(columns => { columns.Bound(p => p.TransporterName).Title(Html.Translate("Transporter Name")) .ClientTemplate("<a href='" + Url.Action("PaymentRequests", "ValidatedPaymentRequest", new { transporterID = "#=TransporterID#" }) + " '>#=TransporterName#</a> "); columns.Bound(p => p.BidContract).Title(Html.Translate("Bid Number")); columns.Bound(p => p.TransporterID).Title(Html.Translate("Actions")) .ClientTemplate("<a href='" + Url.Action("GenerateAgreementTemplate", "BidWinner", new {Area="Procurement", transporterID = "#=TransporterID#" }) + " '>Generate Agreement</a> "); //columns.Command(command => command.Custom("SignContract").Click("OnSignContract")); }) //.Editable(editable => editable.Mode(GridEditMode.InCell)) .Scrollable() .Sortable() .Filterable() .DataSource(dataSource => dataSource .Ajax().Sort(sort => sort.Add("TransporterName").Ascending()) //.PageSize(8) //.Model(model => model.Id(p => p.WoredaHubID)) .Read(read => read.Action("BidWinningTransporters_read", "ValidatedPaymentRequest")) ) )
@using Cats.Areas.Procurement.Models @using Cats.Helpers @using Cats.Models @using Cats.Services.Security @using Kendo.Mvc.UI @{ ViewBag.Title = Html.Translate("Index"); Layout = "~/Views/Shared/_MainLayout.cshtml"; } <h3>Transporters having active order</h3> @(Html.Kendo().Grid<TransporterViewModel>() .Name("grid") .Columns(columns => { columns.Bound(p => p.TransporterName).Title(Html.Translate("Transporter Name")) .ClientTemplate("<a href='" + Url.Action("PaymentRequests", "ValidatedPaymentRequest", new { transporterID = "#=TransporterID#" }) + " '>#=TransporterName#</a> "); columns.Bound(p => p.BidContract).Title(Html.Translate("Bid Number")); columns.Bound(p => p.TransporterID).Title(Html.Translate("Actions")) .ClientTemplate("<a href='" + Url.Action("GenerateAgreementTemplate", "BidWinner", new {Area="Procurement", transporterID = "#=TransporterID#" }) + " '>Generate Agreement</a> "); //columns.Command(command => command.Custom("SignContract").Click("OnSignContract")); }) //.Editable(editable => editable.Mode(GridEditMode.InCell)) .Scrollable() .Sortable() .Filterable() .DataSource(dataSource => dataSource .Ajax() //.PageSize(8) //.Model(model => model.Id(p => p.WoredaHubID)) .Read(read => read.Action("BidWinningTransporters_read", "ValidatedPaymentRequest")) ) )
apache-2.0
C#
524b151a2d2d9acd9e34199fd7f0a275b0cade89
Remove comment - no action needed
markaschell/SoftwareThresher
code/SoftwareThresher/SoftwareThresher/Observations/Observation.cs
code/SoftwareThresher/SoftwareThresher/Observations/Observation.cs
using System.IO; using SoftwareThresher.Settings.Search; using SoftwareThresher.Utilities; namespace SoftwareThresher.Observations { public abstract class Observation { readonly Search search; protected Observation(Search search) { this.search = search; } public virtual bool Failed { get; set; } public abstract string Name { get; } public abstract string Location { get; } public abstract string SystemSpecificString { get; } public virtual Date LastEdit => search.GetLastEditDate(this); public override string ToString() { return $"{Location}{Path.PathSeparator}{Name}"; } } }
using System.IO; using SoftwareThresher.Settings.Search; using SoftwareThresher.Utilities; namespace SoftwareThresher.Observations { public abstract class Observation { readonly Search search; protected Observation(Search search) { this.search = search; } public virtual bool Failed { get; set; } public abstract string Name { get; } public abstract string Location { get; } public abstract string SystemSpecificString { get; } // TODO - push more logic into this class? public virtual Date LastEdit => search.GetLastEditDate(this); public override string ToString() { return $"{Location}{Path.PathSeparator}{Name}"; } } }
mit
C#
d335a8a85c027f4922f66b72e7a11ae2b0b4b400
Remove tests from Travis build until #55 is done
k94ll13nn3/Strinken
travis.cake
travis.cake
////////////////////////////////////////////////////////////////////// // DEPENDENCIES ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // PREPARATION ////////////////////////////////////////////////////////////////////// var framework = "netstandard1.0"; var solutionDir = Directory("./src/") + Directory("Strinken/"); var buildDir = solutionDir + Directory("bin/"); ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Clean") .Does(() => CleanDirectory(buildDir)); Task("Restore") .IsDependentOn("Clean") .Does(() => DotNetCoreRestore()); Task("Build") .IsDependentOn("Restore") .Does(() => { var settings = new DotNetCoreBuildSettings { Configuration = configuration, Framework = framework }; DotNetCoreBuild(solutionDir, settings); }); Task("Run-Unit-Tests") .IsDependentOn("Build") .Does(() => { var settings = new DotNetCoreTestSettings { Configuration = configuration }; DotNetCoreTest("./test/Strinken.Tests/Strinken.Tests.csproj", settings); DotNetCoreTest("./test/Strinken.Public.Tests/Strinken.Public.Tests.csproj", settings); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Build"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
////////////////////////////////////////////////////////////////////// // DEPENDENCIES ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // PREPARATION ////////////////////////////////////////////////////////////////////// var framework = "netstandard1.0"; var solutionDir = Directory("./src/") + Directory("Strinken/"); var buildDir = solutionDir + Directory("bin/"); ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Clean") .Does(() => CleanDirectory(buildDir)); Task("Restore") .IsDependentOn("Clean") .Does(() => DotNetCoreRestore()); Task("Build") .IsDependentOn("Restore") .Does(() => { var settings = new DotNetCoreBuildSettings { Configuration = configuration, Framework = framework }; DotNetCoreBuild(solutionDir, settings); }); Task("Run-Unit-Tests") .IsDependentOn("Build") .Does(() => { var settings = new DotNetCoreTestSettings { Configuration = configuration }; DotNetCoreTest("./test/Strinken.Tests/Strinken.Tests.csproj", settings); DotNetCoreTest("./test/Strinken.Public.Tests/Strinken.Public.Tests.csproj", settings); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Run-Unit-Tests"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
mit
C#
3566ff086a93668fd175d56d0b209948b65ed8d1
Update Assets/MRTK/SDK/Features/Utilities/ConstraintUtils.cs
killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
Assets/MRTK/SDK/Features/Utilities/ConstraintUtils.cs
Assets/MRTK/SDK/Features/Utilities/ConstraintUtils.cs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using UnityEngine; using System.Collections.Generic; using Microsoft.MixedReality.Toolkit.UI; namespace Microsoft.MixedReality.Toolkit.Utilities { /// <summary> /// Utilities for the management of constraints. /// </summary> internal static class ConstraintUtils { /// <summary> /// Adds a constraint to the specified already-sorted list of constraints, maintaining /// execution priority order. SortedSet is not used, as equal priorities /// break duplicate-checking with SortedSet, as well as SortedSet not being /// able to handle runtime-changing exec priorities. /// </summary> /// <param name="constraintList">Sorted list of existing priorites</param> /// <param name="constraint">Constraint to add</param> /// <param name="comparer">ConstraintExecOrderComparer for comparing two constraint priorities</param> internal static void AddWithPriority(ref List<TransformConstraint> constraintList, TransformConstraint constraint, ConstraintExecOrderComparer comparer) { if (constraintList.Contains(constraint)) { return; } if (constraintList.Count == 0 || comparer.Compare(constraintList[constraintList.Count-1], constraint) < 0) { constraintList.Add(constraint); return; } else if (comparer.Compare(constraintList[0], constraint) > 0) { constraintList.Insert(0, constraint); return; } else { int idx = constraintList.BinarySearch(constraint, comparer); if (idx < 0) { // idx will be the two's complement of the index of the // next element that is "larger" than the given constraint. idx = ~idx; } constraintList.Insert(idx, constraint); } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using UnityEngine; using System.Collections.Generic; using Microsoft.MixedReality.Toolkit.UI; namespace Microsoft.MixedReality.Toolkit.Utilities { /// <summary> /// Utilities for the management of constraints. /// </summary> internal static class ConstraintUtils { /// <summary> /// Adds a constraint to the specified already-sorted list of constraints, maintaining /// execution priority order. SortedSet is not used, as equal priorities /// break duplicate-checking with SortedSet, as well as SortedSet not being /// able to handle runtime-changing exec priorities. /// </summary> /// <param name="constraintList">Sorted list of existing priorites</param> /// <param name="constraint">Constraint to add</param> /// <param name="comparer">ConstraintExecOrderComparer for comparing two constraint priorities</param> internal static void AddWithPriority(ref List<TransformConstraint> constraintList, TransformConstraint constraint, ConstraintExecOrderComparer comparer) { if (constraintList.Contains(constraint)) { return; } if (constraintList.Count == 0 || comparer.Compare(constraintList[constraintList.Count-1], constraint) < 0) { constraintList.Add(constraint); return; } else if (comparer.Compare(constraintList[0], constraint) > 0) { constraintList.Insert(0, constraint); return; } else { int idx = constraintList.BinarySearch(constraint, comparer); if(idx < 0) { // idx will be the two's complement of the index of the // next element that is "larger" than the given constraint. idx = ~idx; } constraintList.Insert(idx, constraint); } } } }
mit
C#
694305a6842b69d40be9b27f6474502b9eb48135
Hide links we don't need
mauricedb/Movies-GES,mauricedb/Movies-GES,mauricedb/Movies-GES
Movies-GES/Movies-GES.Web/Views/Shared/_Layout.cshtml
Movies-GES/Movies-GES.Web/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - My ASP.NET Application</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> @Html.ActionLink("Movies GES", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("Movies", "Index", "MovieManagement")</li> <li>@*@Html.ActionLink("Directors", "Index", "DirectorManagement")*@</li> @*<li>@Html.ActionLink("About", "About", "Home")</li> <li>@Html.ActionLink("Contact", "Contact", "Home")</li>*@ </ul> </div> </div> </div> <div class="container body-content"> @RenderBody() <hr /> <footer> <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p> </footer> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - My ASP.NET Application</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("Movies", "Index", "MovieManagement")</li> <li>@Html.ActionLink("Directors", "Index", "DirectorManagement")</li> <li>@Html.ActionLink("About", "About", "Home")</li> <li>@Html.ActionLink("Contact", "Contact", "Home")</li> </ul> </div> </div> </div> <div class="container body-content"> @RenderBody() <hr /> <footer> <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p> </footer> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
mit
C#
2010dbbf595dd544633e196903f2234d2168fd36
optimize test console
tinohager/Nager.AmazonProductAdvertising,tinohager/Nager.AmazonProductAdvertising
Nager.AmazonProductAdvertising.TestConsole/Program.cs
Nager.AmazonProductAdvertising.TestConsole/Program.cs
using Nager.AmazonProductAdvertising.Model; using Nager.AmazonProductAdvertising.Extension; using System; namespace Nager.AmazonProductAdvertising.TestConsole { class Program { static void Main(string[] args) { Console.WriteLine("Please insert accesskey"); var accessKey = Console.ReadLine(); Console.WriteLine("Please insert secretkey"); var secretKey = Console.ReadLine(); var authentication = new AmazonAuthentication(); authentication.AccessKey = accessKey; authentication.SecretKey = secretKey; SearchRequest(authentication); LookupRequest(authentication); CustomRequest(authentication); Console.ReadLine(); } static void SearchRequest(AmazonAuthentication authentication) { var wrapper = new AmazonWrapper(authentication, AmazonEndpoint.DE); var result = wrapper.Search("canon eos", AmazonSearchIndex.Electronics, AmazonResponseGroup.Large); foreach(var item in result.Items.Item) { Console.WriteLine(item.ItemAttributes.Title); } Console.WriteLine("found {0} items", result.Items.Item.Length); } static void LookupRequest(AmazonAuthentication authentication) { var wrapper = new AmazonWrapper(authentication, AmazonEndpoint.DE); var result = wrapper.Lookup("B007KKKJYK"); Console.WriteLine("{0}", result.Items.Item[0].ItemAttributes.Title); } static void CustomRequest(AmazonAuthentication authentication) { var wrapper = new AmazonWrapper(authentication, AmazonEndpoint.DE); var searchQuery = wrapper.ItemSearchOperation("canon eos", AmazonSearchIndex.Electronics); searchQuery = searchQuery.Sort(AmazonSearchSort.Price, AmazonSearchSortOrder.Descending); searchQuery = searchQuery.ItemPage(11); var xml = wrapper.Request(searchQuery); var result = XmlHelper.ParseXml<ItemSearchResponse>(xml); foreach (var item in result.Items.Item) { Console.WriteLine(item.ItemAttributes.Title); } Console.WriteLine("found {0} items", result.Items.Item.Length); } } }
using Nager.AmazonProductAdvertising.Model; using Nager.AmazonProductAdvertising.Extension; using System; namespace Nager.AmazonProductAdvertising.TestConsole { class Program { static void Main(string[] args) { var authentication = new AmazonAuthentication(); authentication.AccessKey = "accesskey"; authentication.SecretKey = "secretkey"; SearchRequest(authentication); LookupRequest(authentication); CustomRequest(authentication); Console.ReadLine(); } static void SearchRequest(AmazonAuthentication authentication) { var wrapper = new AmazonWrapper(authentication, AmazonEndpoint.DE, "nagerat-21"); var result = wrapper.Search("canon eos", AmazonSearchIndex.Electronics, AmazonResponseGroup.Large); foreach(var item in result.Items.Item) { Console.WriteLine(item.ItemAttributes.Title); } Console.WriteLine("found {0} items", result.Items.Item.Length); } static void LookupRequest(AmazonAuthentication authentication) { var wrapper = new AmazonWrapper(authentication, AmazonEndpoint.DE, "nagerat-21"); var result = wrapper.Lookup("B007KKKJYK"); Console.WriteLine("{0}", result.Items.Item[0].ItemAttributes.Title); } static void CustomRequest(AmazonAuthentication authentication) { var wrapper = new AmazonWrapper(authentication, AmazonEndpoint.DE, "nagerat-21"); var searchQuery = wrapper.ItemSearchOperation("canon eos", AmazonSearchIndex.Electronics); searchQuery.Sort(AmazonSearchSort.Price, AmazonSearchSortOrder.Descending); var xml = wrapper.Request(searchQuery); var result = XmlHelper.ParseXml<ItemSearchResponse>(xml); foreach (var item in result.Items.Item) { Console.WriteLine(item.ItemAttributes.Title); } Console.WriteLine("found {0} items", result.Items.Item.Length); } } }
mit
C#
530aa6d78b4a4cffa631cca3223676f88fcbf7d0
Add GridView extension method to get data row style
roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University
R7.University/ControlExtensions/GridViewExtensions.cs
R7.University/ControlExtensions/GridViewExtensions.cs
// // GridViewExtensions.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2015 Roman M. Yagodin // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System.Diagnostics.Contracts; using System.Web.UI.WebControls; using DotNetNuke.Services.Localization; namespace R7.University.ControlExtensions { public static class GridViewExtensions { public static void LocalizeColumns (this GridView gv, string resourceFile) { foreach (DataControlField column in gv.Columns) column.HeaderText = Localization.GetString (column.HeaderText + ".Column", resourceFile); } public static TableItemStyle GetDataRowStyle (this GridView gv, GridViewRow row) { Contract.Requires (row.RowType == DataControlRowType.DataRow); return (row.DataItemIndex % 2 == 0) ? gv.RowStyle : gv.AlternatingRowStyle; } } }
// // GridViewExtensions.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2015 Roman M. Yagodin // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Web.UI.WebControls; using DotNetNuke.Services.Localization; namespace R7.University.ControlExtensions { public static class GridViewExtensions { public static void LocalizeColumns (this GridView gv, string resourceFile) { foreach (DataControlField column in gv.Columns) column.HeaderText = Localization.GetString (column.HeaderText + ".Column", resourceFile); } } }
agpl-3.0
C#
0603ea1afb17f86c513380e38a1e76d045cd03f2
Set InputMinutiaType upon leaving Uninitialised state
SimPrints/SimTemplate,SimPrints/SimTemplate
TemplateBuilderMVVM/ViewModel/States/Uninitialised.cs
TemplateBuilderMVVM/ViewModel/States/Uninitialised.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using TemplateBuilderMVVM.Helpers; using TemplateBuilderMVVM.Model; namespace TemplateBuilderMVVM.ViewModel.States { public class Uninitialised : BaseState { public Uninitialised(TemplateBuilderViewModel outer, StateManager stateMgr) : base(outer, stateMgr) { } public override void OnEnteringState() { // TODO: grey out 'save template button'? } public override void OnLeavingState() { base.OnLeavingState(); m_Outer.InputMinutiaType = MinutiaType.Termination; } public override void PositionInput(Point e) { // Do nothing when no image has been loaded. } public override void PositionMove(Point e) { // Do nothing when no image has been loaded. } public override void RemoveItem(int index) { // Do nothing when no image has been loaded. } public override void SaveTemplate() { // Do nothing when no image has been loaded } public override void SetMinutiaType(MinutiaType type) { // Do nothing when no image has been loaded } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using TemplateBuilderMVVM.Helpers; using TemplateBuilderMVVM.Model; namespace TemplateBuilderMVVM.ViewModel.States { public class Uninitialised : BaseState { public Uninitialised(TemplateBuilderViewModel outer, StateManager stateMgr) : base(outer, stateMgr) { } public override void OnEnteringState() { // TODO: grey out 'save template button'? } public override void PositionInput(Point e) { // Do nothing when no image has been loaded. } public override void PositionMove(Point e) { // Do nothing when no image has been loaded. } public override void RemoveItem(int index) { // Do nothing when no image has been loaded. } public override void SaveTemplate() { // Do nothing when no image has been loaded } public override void SetMinutiaType(MinutiaType type) { // Do nothing when no image has been loaded } } }
bsd-2-clause
C#
ff2784694738ffcdbe58b86f834f2cb649f6a843
change entity type on transition
LagoVista/DeviceAdmin
src/LagoVista.IoT.DeviceAdmin/Models/StateTransition.cs
src/LagoVista.IoT.DeviceAdmin/Models/StateTransition.cs
using LagoVista.Core.Attributes; using LagoVista.Core.Interfaces; using LagoVista.Core.Models; using LagoVista.IoT.DeviceAdmin.Resources; using System.Collections.Generic; using System.Collections.ObjectModel; namespace LagoVista.IoT.DeviceAdmin.Models { [EntityDescription(DeviceAdminDomain.StateMachines, Resources.DeviceLibraryResources.Names.StateTransition_Title, Resources.DeviceLibraryResources.Names.StateTransition_UserHelp, Resources.DeviceLibraryResources.Names.StateTransition_Description, EntityDescriptionAttribute.EntityTypes.SimpleModel, typeof(DeviceLibraryResources))] public class StateTransition { [FormField(LabelResource: Resources.DeviceLibraryResources.Names.StateMachine_Event, HelpResource: DeviceLibraryResources.Names.StateMachine_Transition_EventHelp, FieldType: FieldTypes.ChildItem, ResourceType: typeof(DeviceLibraryResources))] public EntityHeader<Event> Event { get; set; } [FormField(LabelResource: Resources.DeviceLibraryResources.Names.StateMachine_NewState, HelpResource: DeviceLibraryResources.Names.StateMachine_NewState_Help, FieldType: FieldTypes.ChildItem, ResourceType: typeof(DeviceLibraryResources))] public EntityHeader<State> NewState { get; set; } [FormField(LabelResource: Resources.DeviceLibraryResources.Names.StateMachine_Transition_Script, HelpResource: DeviceLibraryResources.Names.StateMachine_Transition_Action_Help, FieldType: FieldTypes.NodeScript, ResourceType: typeof(DeviceLibraryResources))] public string TransitionAction { get; set; } [FormField(LabelResource: Resources.DeviceLibraryResources.Names.Common_Description, FieldType: FieldTypes.MultiLineText, ResourceType: typeof(DeviceLibraryResources))] public string Description { get; set; } } }
using LagoVista.Core.Attributes; using LagoVista.Core.Interfaces; using LagoVista.IoT.DeviceAdmin.Resources; using System.Collections.Generic; using System.Collections.ObjectModel; namespace LagoVista.IoT.DeviceAdmin.Models { [EntityDescription(DeviceAdminDomain.StateMachines, Resources.DeviceLibraryResources.Names.StateTransition_Title, Resources.DeviceLibraryResources.Names.StateTransition_UserHelp, Resources.DeviceLibraryResources.Names.StateTransition_Description, EntityDescriptionAttribute.EntityTypes.SimpleModel, typeof(DeviceLibraryResources))] public class StateTransition { [FormField(LabelResource: Resources.DeviceLibraryResources.Names.StateMachine_Event, HelpResource: DeviceLibraryResources.Names.StateMachine_Transition_EventHelp, FieldType: FieldTypes.ChildItem, ResourceType: typeof(DeviceLibraryResources))] public IEntityHeader Event { get; set; } [FormField(LabelResource: Resources.DeviceLibraryResources.Names.StateMachine_NewState, HelpResource: DeviceLibraryResources.Names.StateMachine_NewState_Help, FieldType: FieldTypes.ChildItem, ResourceType: typeof(DeviceLibraryResources))] public IEntityHeader NewState { get; set; } [FormField(LabelResource: Resources.DeviceLibraryResources.Names.StateMachine_Transition_Script, HelpResource: DeviceLibraryResources.Names.StateMachine_Transition_Action_Help, FieldType: FieldTypes.NodeScript, ResourceType: typeof(DeviceLibraryResources))] public string TransitionAction { get; set; } [FormField(LabelResource: Resources.DeviceLibraryResources.Names.Common_Description, FieldType: FieldTypes.MultiLineText, ResourceType: typeof(DeviceLibraryResources))] public string Description { get; set; } } }
mit
C#
14541ae2ba3567340758f1a080d57154be1e30de
Remove incorrect permission check on "Design" admin menu (#7316)
xkproject/Orchard2,xkproject/Orchard2,xkproject/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2
src/OrchardCore.Modules/OrchardCore.Themes/AdminMenu.cs
src/OrchardCore.Modules/OrchardCore.Themes/AdminMenu.cs
using System; using System.Threading.Tasks; using Microsoft.Extensions.Localization; using OrchardCore.Navigation; namespace OrchardCore.Themes { public class AdminMenu : INavigationProvider { private readonly IStringLocalizer S; public AdminMenu(IStringLocalizer<AdminMenu> localizer) { S = localizer; } public Task BuildNavigationAsync(string name, NavigationBuilder builder) { if (!String.Equals(name, "admin", StringComparison.OrdinalIgnoreCase)) { return Task.CompletedTask; } builder .Add(S["Design"], NavigationConstants.AdminMenuDesignPosition, design => design .AddClass("themes").Id("themes") .Add(S["Themes"], "Themes", installed => installed .Action("Index", "Admin", new { area = "OrchardCore.Themes" }) .Permission(Permissions.ApplyTheme) .LocalNav() ) ); return Task.CompletedTask; } } }
using System; using System.Threading.Tasks; using Microsoft.Extensions.Localization; using OrchardCore.Navigation; namespace OrchardCore.Themes { public class AdminMenu : INavigationProvider { private readonly IStringLocalizer S; public AdminMenu(IStringLocalizer<AdminMenu> localizer) { S = localizer; } public Task BuildNavigationAsync(string name, NavigationBuilder builder) { if (!String.Equals(name, "admin", StringComparison.OrdinalIgnoreCase)) { return Task.CompletedTask; } builder .Add(S["Design"], NavigationConstants.AdminMenuDesignPosition, design => design .AddClass("themes").Id("themes") .Permission(Permissions.ApplyTheme) .Add(S["Themes"], "Themes", installed => installed .Action("Index", "Admin", new { area = "OrchardCore.Themes" }) .Permission(Permissions.ApplyTheme) .LocalNav() ) ); return Task.CompletedTask; } } }
bsd-3-clause
C#
dfe4b6707c395f0de40d5bbb1d4db510dca79ef3
Update IRepo base
generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork
src/Smooth.IoC.Dapper.Repository.UnitOfWork/Repo/IRepositoryBase.cs
src/Smooth.IoC.Dapper.Repository.UnitOfWork/Repo/IRepositoryBase.cs
using System.Collections.Generic; using System.Threading.Tasks; using Smooth.IoC.Dapper.Repository.UnitOfWork.Data; using Smooth.IoC.Dapper.Repository.UnitOfWork.Entities; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo { public interface IRepositoryBase { } }
using System.Collections.Generic; using System.Threading.Tasks; using Smooth.IoC.Dapper.Repository.UnitOfWork.Data; using Smooth.IoC.Dapper.Repository.UnitOfWork.Entities; namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo { public interface IRepository<TEntity, TPk> where TEntity : class, IEntity<TPk> { TEntity GetKey(TPk key, ISession session = null); Task<TEntity> GetKeyAsync(TPk key, ISession session = null); TEntity Get(TEntity entity, ISession session = null); Task<TEntity> GetAsync(TEntity entity, ISession session = null); IEnumerable<TEntity> GetAll(ISession session = null); Task<IEnumerable<TEntity>> GetAllAsync(ISession session = null); TPk SaveOrUpdate(TEntity entity, IUnitOfWork uow); Task<TPk> SaveOrUpdateAsync(TEntity entity, IUnitOfWork uow); } }
mit
C#
464fc8a15fe48e8c03b5573c467b4c45486f5581
Update Default.cshtml
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
samples/MusicStore/Views/Shared/Components/GenreMenu/Default.cshtml
samples/MusicStore/Views/Shared/Components/GenreMenu/Default.cshtml
@model IEnumerable<string> <li class="dropdown"> <a asp-area="" asp-controller="Store" asp-action="Index" class="dropdown-toggle" data-toggle="dropdown">Store <b class="caret"></b></a> <ul class="dropdown-menu"> @foreach (var genreName in Model) { <li> <a asp-area="" asp-controller="Store" asp-action="Browse" asp-route-Genre="@genreName">@genreName</a> </li> } <li class="divider"></li> <li> <a asp-area="" asp-controller="Store" asp-action="Index">More...</a> </li> </ul> </li>
@model IEnumerable<string> <li class="dropdown"> <a asp-area="" asp-controller="Store" asp-action="Index" class="dropdown-toggle" data-toggle="dropdown">Store <b class="caret"></b></a> <ul class="dropdown-menu"> @foreach (var genreName in Model) { <li> <a asp-area="" asp-controller="Store" asp-action="Browse" asp-route-Genre="@genreName">@genreName</a> </li> } <li class="divider"></li> <li> <a asp-controller="Store" asp-action="Index">More...</a> </li> </ul> </li>
apache-2.0
C#
a553aea4a0b399e222dd85fa7a3691885a41bde0
Remove stale todo comments
ddobric/durabletask,affandar/durabletask,jasoneilts/durabletask,Azure/durabletask,yonglehou/durabletask
Framework/JsonDataConverter.cs
Framework/JsonDataConverter.cs
// ---------------------------------------------------------------------------------- // 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. // ---------------------------------------------------------------------------------- namespace DurableTask { using System; using System.Globalization; using System.IO; using System.Text; using Newtonsoft.Json; public class JsonDataConverter : DataConverter { readonly JsonSerializer serializer; public JsonDataConverter() : this(new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.Objects}) { } public JsonDataConverter(JsonSerializerSettings settings) { serializer = JsonSerializer.Create(settings); } public override string Serialize(object value) { var sb = new StringBuilder(0x100); var textWriter = new StringWriter(sb, CultureInfo.InvariantCulture); using (var writer = new JsonTextWriter(textWriter)) { writer.Formatting = Formatting.None; serializer.Serialize(writer, value); } return textWriter.ToString(); } public override object Deserialize(string data, Type objectType) { if (data == null) { return null; } var reader = new StringReader(data); return serializer.Deserialize(new JsonTextReader(reader), objectType); } } }
// ---------------------------------------------------------------------------------- // 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. // ---------------------------------------------------------------------------------- namespace DurableTask { using System; using System.Globalization; using System.IO; using System.Text; using Newtonsoft.Json; // TODO : // 1. Have to figure out the licensing issues with using Json.Net // 2. Must have a mechanism by which a user can simply pass in an XmlObjectSerializer based serializer rather than having to wrap // it in a dataconverter public class JsonDataConverter : DataConverter { readonly JsonSerializer serializer; public JsonDataConverter() : this(new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.Objects}) { } public JsonDataConverter(JsonSerializerSettings settings) { serializer = JsonSerializer.Create(settings); } public override string Serialize(object value) { var sb = new StringBuilder(0x100); var textWriter = new StringWriter(sb, CultureInfo.InvariantCulture); using (var writer = new JsonTextWriter(textWriter)) { writer.Formatting = Formatting.None; serializer.Serialize(writer, value); } return textWriter.ToString(); } public override object Deserialize(string data, Type objectType) { if (data == null) { return null; } var reader = new StringReader(data); return serializer.Deserialize(new JsonTextReader(reader), objectType); } } }
apache-2.0
C#
d14e9acbe766892af9f35927ea400b82beded918
Use correct repository owner for GitHub link.
github/VisualStudio,github/VisualStudio,github/VisualStudio
src/GitHub.InlineReviews/ViewModels/InlineCommentThreadViewModel.cs
src/GitHub.InlineReviews/ViewModels/InlineCommentThreadViewModel.cs
using System; using System.Collections.Generic; using System.Globalization; using System.Reactive.Linq; using System.Threading.Tasks; using GitHub.Api; using GitHub.Extensions; using GitHub.Models; using GitHub.Services; using Octokit; using ReactiveUI; namespace GitHub.InlineReviews.ViewModels { /// <summary> /// A thread of inline comments (aka Pull Request Review Comments). /// </summary> public class InlineCommentThreadViewModel : CommentThreadViewModel { /// <summary> /// Initializes a new instance of the <see cref="InlineCommentThreadViewModel"/> class. /// </summary> /// <param name="apiClient">The API client to use to post/update comments.</param> /// <param name="session">The current PR review session.</param> public InlineCommentThreadViewModel( IPullRequestSession session, IEnumerable<IPullRequestReviewCommentModel> comments) : base(session.User) { Guard.ArgumentNotNull(session, nameof(session)); Session = session; PostComment = ReactiveCommand.CreateAsyncTask( Observable.Return(true), DoPostComment); foreach (var comment in comments) { Comments.Add(new CommentViewModel(this, CurrentUser, comment)); } Comments.Add(CommentViewModel.CreatePlaceholder(this, CurrentUser)); } /// <summary> /// Gets the current pull request review session. /// </summary> public IPullRequestSession Session { get; } /// <inheritdoc/> public override Uri GetCommentUrl(int id) { return new Uri(string.Format( CultureInfo.InvariantCulture, "{0}/pull/{1}#discussion_r{2}", Session.LocalRepository.CloneUrl.ToRepositoryUrl(Session.RepositoryOwner), Session.PullRequest.Number, id)); } async Task<ICommentModel> DoPostComment(object parameter) { Guard.ArgumentNotNull(parameter, nameof(parameter)); var body = (string)parameter; var replyId = Comments[0].Id; return await Session.PostReviewComment(body, replyId); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Reactive.Linq; using System.Threading.Tasks; using GitHub.Api; using GitHub.Extensions; using GitHub.Models; using GitHub.Services; using Octokit; using ReactiveUI; namespace GitHub.InlineReviews.ViewModels { /// <summary> /// A thread of inline comments (aka Pull Request Review Comments). /// </summary> public class InlineCommentThreadViewModel : CommentThreadViewModel { /// <summary> /// Initializes a new instance of the <see cref="InlineCommentThreadViewModel"/> class. /// </summary> /// <param name="apiClient">The API client to use to post/update comments.</param> /// <param name="session">The current PR review session.</param> public InlineCommentThreadViewModel( IPullRequestSession session, IEnumerable<IPullRequestReviewCommentModel> comments) : base(session.User) { Guard.ArgumentNotNull(session, nameof(session)); Session = session; PostComment = ReactiveCommand.CreateAsyncTask( Observable.Return(true), DoPostComment); foreach (var comment in comments) { Comments.Add(new CommentViewModel(this, CurrentUser, comment)); } Comments.Add(CommentViewModel.CreatePlaceholder(this, CurrentUser)); } /// <summary> /// Gets the current pull request review session. /// </summary> public IPullRequestSession Session { get; } /// <inheritdoc/> public override Uri GetCommentUrl(int id) { return new Uri(string.Format( CultureInfo.InvariantCulture, "{0}/pull/{1}#discussion_r{2}", Session.LocalRepository.CloneUrl.ToRepositoryUrl(), Session.PullRequest.Number, id)); } async Task<ICommentModel> DoPostComment(object parameter) { Guard.ArgumentNotNull(parameter, nameof(parameter)); var body = (string)parameter; var replyId = Comments[0].Id; return await Session.PostReviewComment(body, replyId); } } }
mit
C#
1a07273910438d87cc89aea4af337e8615ad6483
Fix copying of markdown result.
JohanLarsson/Gu.State,JohanLarsson/Gu.ChangeTracking,JohanLarsson/Gu.State
Gu.State.Benchmarks/Program.cs
Gu.State.Benchmarks/Program.cs
// ReSharper disable UnusedMember.Local namespace Gu.State.Benchmarks { using System; using System.Collections.Generic; using System.IO; using System.Linq; using BenchmarkDotNet.Reports; using BenchmarkDotNet.Running; public static class Program { public static void Main() { foreach (var summary in RunSingle<EqualByComplexType>()) { CopyResult(summary); } } private static IEnumerable<Summary> RunAll() => new BenchmarkSwitcher(typeof(Program).Assembly).RunAll(); private static IEnumerable<Summary> RunSingle<T>() => new[] { BenchmarkRunner.Run<T>() }; private static void CopyResult(Summary summary) { var trimmedTitle = summary.Title.Split('.').Last().Split('-').First(); Console.WriteLine(trimmedTitle); var sourceFileName = FindMdFile(); var destinationFileName = Path.ChangeExtension(FindCsFile(), ".md"); Console.WriteLine($"Copy: {sourceFileName} -> {destinationFileName}"); File.Copy(sourceFileName, destinationFileName, overwrite: true); string FindMdFile() { return Directory.EnumerateFiles(summary.ResultsDirectoryPath, $"*{trimmedTitle}-report-github.md") .Single(); } string FindCsFile() { return Directory.EnumerateFiles( AppDomain.CurrentDomain.BaseDirectory.Split(new[] { "\\bin\\" }, StringSplitOptions.RemoveEmptyEntries).First(), $"{trimmedTitle}.cs", SearchOption.AllDirectories) .Single(); } } } }
// ReSharper disable UnusedMember.Local namespace Gu.State.Benchmarks { using System; using System.Collections.Generic; using System.IO; using System.Linq; using BenchmarkDotNet.Reports; using BenchmarkDotNet.Running; public static class Program { public static void Main() { foreach (var summary in RunSingle<EqualByComplexType>()) { CopyResult(summary); } } private static IEnumerable<Summary> RunAll() => new BenchmarkSwitcher(typeof(Program).Assembly).RunAll(); private static IEnumerable<Summary> RunSingle<T>() => new[] { BenchmarkRunner.Run<T>() }; private static void CopyResult(Summary summary) { var sourceFileName = Directory.EnumerateFiles(summary.ResultsDirectoryPath, $"*{summary.Title}-report-github.md") .Single(); var destinationFileName = Path.ChangeExtension(FindCsFile(), ".md"); Console.WriteLine($"Copy: {sourceFileName} -> {destinationFileName}"); File.Copy(sourceFileName, destinationFileName, overwrite: true); string FindCsFile() { return Directory.EnumerateFiles( AppDomain.CurrentDomain.BaseDirectory.Split(new[] { "\\bin\\" }, StringSplitOptions.RemoveEmptyEntries).First(), $"{summary.Title.Split('.').Last()}.cs", SearchOption.AllDirectories) .Single(); } } } }
mit
C#
dafc2a3acb7e91a1edb69fd09a918c2f1e3a93fd
tidy up controller
NaamloosDT/ModCore,NaamloosDT/ModCore
ModCore/CoreApi/Controllers/ApiController.cs
ModCore/CoreApi/Controllers/ApiController.cs
using Microsoft.AspNetCore.Mvc; using ModCore.CoreApi.Entities; using ModCore.Database; using ModCore.Entities; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ModCore.CoreApi.Controllers { [Route("api")] public class ApiController : Controller { private ModCore core; public ApiController(CoreContainer cont) { this.core = cont.mcore; } public string Index() { return "ModCore API"; } [HttpGet("token/{token}")] public bool Token(string token) { // allow cross-domain shit for w/e reason Response.Headers.Add("Access-Control-Allow-Origin", "*"); return core.SharedData.ApiToken == token; } // GET ping [HttpGet("ping")] public string Ping() { return "pong!"; } [HttpGet("default")] public string Dp() { return "Default prefix: " + core.SharedData.DefaultPrefix; } [HttpGet("roles/{gid}")] public string Roles(ulong gid) { // Check token. var h = Request.Headers["Token"]; if (string.IsNullOrEmpty(h) || core.SharedData.ApiToken != h) { this.Unauthorized(); return null; } var arl = new ApiRoleList(); var guildsfound = core.Shards.SelectMany(x => x.Client.Guilds.Values.Where(g => g.Id == gid)).ToArray(); if (guildsfound.Length > 0) { foreach (var r in guildsfound[0].Roles) { arl.Roles.Add(new ApiRole { RoleId = r.Id, RoleName = r.Name }); } Response.ContentType = "application/json"; return JsonConvert.SerializeObject(arl); } NotFound(); return null; } [HttpGet("emptyconfig")] public JObject EmptyConfig() { // allow cross-domain shit for w/e reason Response.Headers.Add("Access-Control-Allow-Origin", "*"); Response.ContentType = "application/json"; return JObject.FromObject(new GuildSettings() { Prefix = "data served by ModCore."}); } } }
using Microsoft.AspNetCore.Mvc; using ModCore.CoreApi.Entities; using ModCore.Database; using ModCore.Entities; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ModCore.CoreApi.Controllers { [Route("api")] public class ApiController : Controller { private ModCore core; public ApiController(CoreContainer cont) { this.core = cont.mcore; } public string Index() { return "ModCore API"; } [HttpGet("token/{token}")] public bool Token(string token) { // allow cross-domain shit for w/e reason Response.Headers.Add("Access-Control-Allow-Origin", "*"); if (core.SharedData.ApiToken == token) return true; return false; } // GET ping [HttpGet("ping")] public string Ping() { return "pong!"; } [HttpGet("default")] public string Dp() { return "Default prefix: " + core.SharedData.DefaultPrefix; } [HttpGet("roles/{gid}")] public string Roles(ulong gid) { // Check token. var h = Request.Headers["Token"]; if (string.IsNullOrEmpty(h) || core.SharedData.ApiToken != h) { this.Unauthorized(); return null; } var arl = new ApiRoleList(); var guildsfound = core.Shards.SelectMany(x => x.Client.Guilds.Values.Where(g => g.Id == gid)); if(guildsfound.Count() > 0) { foreach (var r in guildsfound.First().Roles) { arl.Roles.Add(new ApiRole() { RoleId = r.Id, RoleName = r.Name }); } Response.ContentType = "application/json"; return JsonConvert.SerializeObject(arl); } NotFound(); return null; } [HttpGet("emptyconfig")] public JObject EmptyConfig() { // allow cross-domain shit for w/e reason Response.Headers.Add("Access-Control-Allow-Origin", "*"); Response.ContentType = "application/json"; return JObject.FromObject(new GuildSettings() { Prefix = "data served by ModCore."}); } } }
mit
C#
1bb3b0e8f25cdc8d7fe7e217476b3d4c778c0ea2
Bump version to 0.8.3
quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot
CactbotOverlay/Properties/AssemblyInfo.cs
CactbotOverlay/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("CactbotOverlay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CactbotOverlay")] [assembly: AssemblyCopyright("Copyright 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")] // Version: // - Major Version // - Minor Version // - Build Number // - Revision // GitHub has only 3 version components, so Revision should always be 0. [assembly: AssemblyVersion("0.8.3.0")] [assembly: AssemblyFileVersion("0.8.3.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("CactbotOverlay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CactbotOverlay")] [assembly: AssemblyCopyright("Copyright 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")] // Version: // - Major Version // - Minor Version // - Build Number // - Revision // GitHub has only 3 version components, so Revision should always be 0. [assembly: AssemblyVersion("0.8.2.0")] [assembly: AssemblyFileVersion("0.8.2.0")]
apache-2.0
C#
294340279eb5614a8a6d1c23d305b6ba9aa5a174
Add inputting test coverage
NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu
osu.Game.Tests/Visual/SongSelect/TestSceneSongSelectFooter.cs
osu.Game.Tests/Visual/SongSelect/TestSceneSongSelectFooter.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics; using osu.Game.Screens.Select; using osuTK.Input; namespace osu.Game.Tests.Visual.SongSelect { public class TestSceneSongSelectFooter : OsuManualInputManagerTestScene { private FooterButtonRandom randomButton; private bool nextRandomCalled; private bool previousRandomCalled; [SetUp] public void SetUp() => Schedule(() => { nextRandomCalled = false; previousRandomCalled = false; Footer footer; Child = footer = new Footer { Anchor = Anchor.Centre, Origin = Anchor.Centre, }; footer.AddButton(new FooterButtonMods(), null); footer.AddButton(randomButton = new FooterButtonRandom { NextRandom = () => nextRandomCalled = true, PreviousRandom = () => previousRandomCalled = true, }, null); footer.AddButton(new FooterButtonOptions(), null); }); [Test] public void TestFooterRandom() { AddStep("press F2", () => InputManager.Key(Key.F2)); AddAssert("next random invoked", () => nextRandomCalled && !previousRandomCalled); } [Test] public void TestFooterRandomViaMouse() { AddStep("click button", () => { InputManager.MoveMouseTo(randomButton); InputManager.Click(MouseButton.Left); }); AddAssert("next random invoked", () => nextRandomCalled && !previousRandomCalled); } [Test] public void TestFooterRewind() { AddStep("press Shift+F2", () => { InputManager.PressKey(Key.LShift); InputManager.PressKey(Key.F2); InputManager.ReleaseKey(Key.F2); InputManager.ReleaseKey(Key.LShift); }); AddAssert("previous random invoked", () => previousRandomCalled && !nextRandomCalled); } [Test] public void TestFooterRewindViaMouse() { AddStep("shift + click button", () => { InputManager.PressKey(Key.LShift); InputManager.MoveMouseTo(randomButton); InputManager.Click(MouseButton.Left); InputManager.ReleaseKey(Key.LShift); }); AddAssert("previous random invoked", () => previousRandomCalled && !nextRandomCalled); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Game.Screens.Select; namespace osu.Game.Tests.Visual.SongSelect { public class TestSceneSongSelectFooter : OsuManualInputManagerTestScene { public TestSceneSongSelectFooter() { AddStep("Create footer", () => { Footer footer; AddRange(new Drawable[] { footer = new Footer { Anchor = Anchor.Centre, Origin = Anchor.Centre, } }); footer.AddButton(new FooterButtonMods(), null); footer.AddButton(new FooterButtonRandom { NextRandom = () => { }, PreviousRandom = () => { }, }, null); footer.AddButton(new FooterButtonOptions(), null); }); } } }
mit
C#
af20e892a33f1256f7791d73c3408da9fb579468
Remove over zealous tracing
croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia.com.au,croquet-australia/website-application,croquet-australia/website-application,croquet-australia/website-application,croquet-australia/website-application
source/CroquetAustralia.Library/Authentication/Identity/InMemoryUserStore-IUserStore.cs
source/CroquetAustralia.Library/Authentication/Identity/InMemoryUserStore-IUserStore.cs
using System; using System.Threading.Tasks; using Anotar.LibLog; using Microsoft.AspNet.Identity; using NullGuard; namespace CroquetAustralia.Library.Authentication.Identity { /// <summary> /// Implements <see cref="IUserStore{TUser,TKey}" />. /// </summary> public partial class InMemoryUserStore // : IUserStore<IdentityUser, Guid> { public Task CreateAsync(IdentityUser user) { LogTo.Trace("CreateAsync(user: {0})", user.ToLogString()); return AddIdentityUserAsync(user); } public Task DeleteAsync(IdentityUser user) { LogTo.Trace("DeleteAsync(IdentityUser user)"); throw new NotImplementedException(); } public void Dispose() { } [return: AllowNull] public async Task<IdentityUser> FindByIdAsync(Guid userId) { LogTo.Trace("FindByIdAsync(userId: {0})", userId); var identityUser = await FindIdentityUserAsync(pair => pair.Key.Id == userId); LogTo.Debug("FindByIdAsync(userId: {0}) => found: {1}", userId, identityUser != null); return identityUser; } [return: AllowNull] public async Task<IdentityUser> FindByNameAsync(string userName) { LogTo.Trace("FindByNameAsync(userName: {0})", userName); var identityUser = await FindIdentityUserAsync(pair => pair.Key.UserName == userName); LogTo.Debug("FindByNameAsync(userName: {0}) => found: {1}", userName, identityUser != null); return identityUser; } public Task UpdateAsync(IdentityUser user) { LogTo.Trace("UpdateAsync(user: {0})", user.ToLogString()); // In memory store so nothing to update. return Task.FromResult(true); } } }
using System; using System.Threading.Tasks; using Anotar.LibLog; using Microsoft.AspNet.Identity; using NullGuard; namespace CroquetAustralia.Library.Authentication.Identity { /// <summary> /// Implements <see cref="IUserStore{TUser,TKey}" />. /// </summary> public partial class InMemoryUserStore // : IUserStore<IdentityUser, Guid> { public Task CreateAsync(IdentityUser user) { LogTo.Trace("CreateAsync(user: {0})", user.ToLogString()); return AddIdentityUserAsync(user); } public Task DeleteAsync(IdentityUser user) { LogTo.Trace("DeleteAsync(IdentityUser user)"); throw new NotImplementedException(); } public void Dispose() { LogTo.Trace("Dispose()"); } [return: AllowNull] public async Task<IdentityUser> FindByIdAsync(Guid userId) { LogTo.Trace("FindByIdAsync(userId: {0})", userId); var identityUser = await FindIdentityUserAsync(pair => pair.Key.Id == userId); LogTo.Debug("FindByIdAsync(userId: {0}) => found: {1}", userId, identityUser != null); return identityUser; } [return: AllowNull] public async Task<IdentityUser> FindByNameAsync(string userName) { LogTo.Trace("FindByNameAsync(userName: {0})", userName); var identityUser = await FindIdentityUserAsync(pair => pair.Key.UserName == userName); LogTo.Debug("FindByNameAsync(userName: {0}) => found: {1}", userName, identityUser != null); return identityUser; } public Task UpdateAsync(IdentityUser user) { LogTo.Trace("UpdateAsync(user: {0})", user.ToLogString()); // In memory store so nothing to update. return Task.FromResult(true); } } }
mit
C#
89f8ab7d80d009df3add07f2b7c571441efb5582
Set version to 1
turtle-box-games/leaf-csharp
Leaf/Leaf/Versions/V1Engine.cs
Leaf/Leaf/Versions/V1Engine.cs
using System.IO; using Leaf.Nodes; namespace Leaf.Versions { /// <summary> /// First version of the node engine. /// </summary> public class V1Engine : Engine { /// <summary> /// Numerical version used to distinguish this engine from others. /// For this engine, the value is 1. /// </summary> public override int Version { get; } = 1; /// <summary> /// Create a header that contains the node structure information that the engine can use later after serialization. /// </summary> /// <return>Version 1 header containing information on how the nodes are structured.</return> /// <seealso cref="V1Header"/> internal override Header CreateHeader() { throw new System.NotImplementedException(); } /// <summary> /// Reads a root node (structure) from a stream. /// </summary> /// <param name="reader">Reader used to pull data from the stream.</param> /// <returns>Root node (structure).</returns> internal override Node ReadStructure(BinaryReader reader) { throw new System.NotImplementedException(); } /// <summary> /// Writes a root node (structure) to a stream. /// </summary> /// <param name="writer">Writer used to put data into the stream.</param> /// <param name="node">Root node (structure).</param> internal override void WriteStructure(BinaryWriter writer, Node node) { throw new System.NotImplementedException(); } } }
using System.IO; using Leaf.Nodes; namespace Leaf.Versions { /// <summary> /// First version of the node engine. /// </summary> public class V1Engine : Engine { /// <summary> /// Numerical version used to distinguish this engine from others. /// For this engine, the value is 1. /// </summary> public override int Version { get; } /// <summary> /// Create a header that contains the node structure information that the engine can use later after serialization. /// </summary> /// <return>Version 1 header containing information on how the nodes are structured.</return> /// <seealso cref="V1Header"/> internal override Header CreateHeader() { throw new System.NotImplementedException(); } /// <summary> /// Reads a root node (structure) from a stream. /// </summary> /// <param name="reader">Reader used to pull data from the stream.</param> /// <returns>Root node (structure).</returns> internal override Node ReadStructure(BinaryReader reader) { throw new System.NotImplementedException(); } /// <summary> /// Writes a root node (structure) to a stream. /// </summary> /// <param name="writer">Writer used to put data into the stream.</param> /// <param name="node">Root node (structure).</param> internal override void WriteStructure(BinaryWriter writer, Node node) { throw new System.NotImplementedException(); } } }
mit
C#
9510dd698c7a347cefcc0ffc9a2ad3a03ba6583d
Add support for non-scalar properties in GetAttribute command
NetlifeBackupSolutions/Winium.StoreApps,goldbillka/Winium.StoreApps,NetlifeBackupSolutions/Winium.StoreApps,2gis/Winium.StoreApps,krishachetan89/Winium.StoreApps,goldbillka/Winium.StoreApps,2gis/Winium.StoreApps,krishachetan89/Winium.StoreApps
WindowsUniversalAppDriver/WindowsUniversalAppDriver.InnerServer/Commands/GetElementAttributeCommand.cs
WindowsUniversalAppDriver/WindowsUniversalAppDriver.InnerServer/Commands/GetElementAttributeCommand.cs
namespace WindowsUniversalAppDriver.InnerServer.Commands { using System; using System.Reflection; using Newtonsoft.Json; using WindowsUniversalAppDriver.Common; internal class GetElementAttributeCommand : CommandBase { #region Public Properties public string ElementId { get; set; } #endregion #region Public Methods and Operators public override string DoImpl() { var element = this.Automator.WebElements.GetRegisteredElement(this.ElementId); object value; string attributeName = null; if (this.Parameters.TryGetValue("NAME", out value)) { attributeName = value.ToString(); } if (attributeName == null) { return this.JsonResponse(ResponseStatus.Success, null); } var properties = attributeName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); object propertyObject = element; foreach (var property in properties) { propertyObject = GetProperty(propertyObject, property); if (propertyObject == null) { break; } } /* GetAttribute command should return: null if no property was found, * property value as plain string if property is scalar or string, * JSON encoded property if property is Lists, Dictionary or other nonscalar types */ var propertyValue = SerializeObjectAsString(propertyObject); return this.JsonResponse(ResponseStatus.Success, propertyValue); } #endregion #region Methods private static object GetProperty(object obj, string propertyName) { var property = obj.GetType().GetRuntimeProperty(propertyName); return property == null ? null : property.GetValue(obj, null); } private static bool IsTypeSerializedUsingToString(Type type) { // Strings should be serialized as plain strings return type == typeof(string) || type.GetTypeInfo().IsPrimitive; } private static string SerializeObjectAsString(object obj) { if (obj == null) { return null; } // Serialize basic types as palin strings if (IsTypeSerializedUsingToString(obj.GetType())) { return obj.ToString(); } // Serialize other data types as JSON return JsonConvert.SerializeObject(obj); } #endregion } }
namespace WindowsUniversalAppDriver.InnerServer.Commands { using System; using System.Reflection; using WindowsUniversalAppDriver.Common; internal class GetElementAttributeCommand : CommandBase { #region Public Properties public string ElementId { get; set; } #endregion #region Public Methods and Operators public override string DoImpl() { var element = this.Automator.WebElements.GetRegisteredElement(this.ElementId); object value; string attributeName = null; if (this.Parameters.TryGetValue("NAME", out value)) { attributeName = value.ToString(); } if (attributeName == null) { return this.JsonResponse(ResponseStatus.Success, null); } var properties = attributeName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); object propertyValueObject = element; foreach (var property in properties) { propertyValueObject = GetProperty(propertyValueObject, property); if (propertyValueObject == null) { break; } } var propertyValue = propertyValueObject == null ? null : propertyValueObject.ToString(); return this.JsonResponse(ResponseStatus.Success, propertyValue); } private static object GetProperty(object obj, string propertyName) { var property = obj.GetType().GetRuntimeProperty(propertyName); return property == null ? null : property.GetValue(obj, null); } #endregion } }
mpl-2.0
C#
183ab64b37545a812cf05759d361450fb6d602e7
Fix warning in RoslynToolchain
alinasmirnova/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,Ky7m/BenchmarkDotNet,Ky7m/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,Ky7m/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,Ky7m/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,Teknikaali/BenchmarkDotNet
src/BenchmarkDotNet.Toolchains.Roslyn/Toolchains/RoslynToolchain.cs
src/BenchmarkDotNet.Toolchains.Roslyn/Toolchains/RoslynToolchain.cs
using BenchmarkDotNet.Toolchains.Classic; using JetBrains.Annotations; namespace BenchmarkDotNet.Toolchains { /// <summary> /// Build a benchmark program with the Roslyn compiler. /// </summary> public class RoslynToolchain : Toolchain { /// <summary> /// Creates new instance of RoslynToolchain. /// </summary> [PublicAPI("Used in auto-generated .exe when this toolchain is set explicitly in Job definition")] public RoslynToolchain() : base("Classic", new RoslynGenerator(), new RoslynBuilder(), new Executor()) { } } }
using BenchmarkDotNet.Toolchains.Classic; using JetBrains.Annotations; namespace BenchmarkDotNet.Toolchains { /// <summary> /// Build a benchmark program with the Roslyn compiler. /// </summary> public class RoslynToolchain : Toolchain { [PublicAPI("Used in auto-generated .exe when this toolchain is set explicitly in Job definition")] public RoslynToolchain() : base("Classic", new RoslynGenerator(), new RoslynBuilder(), new Executor()) { } } }
mit
C#
c4ecef14d7fb7ec67673184f331d841ba267ee21
Add documentation.
PombeirP/T4Factories
GenerateT4FactoryWithContractAttribute.cs
GenerateT4FactoryWithContractAttribute.cs
using System; namespace T4Factories { /// <summary> /// This attribute tells the T4 template to automatically generate a factory for the type this attribute is applied to. /// </summary> public class GenerateT4FactoryWithContractAttribute : Attribute { /// <summary> /// Initializes a new instance of the <see cref="GenerateT4FactoryWithContractAttribute"/> class, telling the T4 template to automatically generate a factory for the type this attribute is applied to. /// </summary> /// <remarks> /// The contract type is assumed to be an interface with the same name as the target class (e.g. ContractType for Foo is IFoo). /// </remarks> public GenerateT4FactoryWithContractAttribute() { } /// <summary> /// Initializes a new instance of the <see cref="GenerateT4FactoryWithContractAttribute"/> class, telling the T4 template to automatically generate a factory for the type this attribute is applied to. /// </summary> /// <param name="contractType"> /// The interface representing the return value of the factory method. /// </param> public GenerateT4FactoryWithContractAttribute(Type contractType) { this.ContractType = contractType; } /// <summary> /// Gets the interface representing the return value of the factory method. /// </summary> public Type ContractType { get; private set; } } }
using System; namespace T4Factories { public class GenerateT4FactoryWithContractAttribute : Attribute { public Type ContractType { get; private set; } public GenerateT4FactoryWithContractAttribute() { } public GenerateT4FactoryWithContractAttribute(Type contractType) { ContractType = contractType; } } }
mit
C#
3d8080684ba10d98d4f1693e159f3413d4c7c25e
Make AttributeLookupCache thread safe.
peeedge/mobile,eatskolnikov/mobile,eatskolnikov/mobile,ZhangLeiCharles/mobile,masterrr/mobile,peeedge/mobile,ZhangLeiCharles/mobile,masterrr/mobile,eatskolnikov/mobile
Phoebe/Data/AttributeLookupCache.cs
Phoebe/Data/AttributeLookupCache.cs
using System; using System.Collections.Generic; namespace Toggl.Phoebe.Data { public class AttributeLookupCache<T> where T : Attribute { private readonly Dictionary<Type, Dictionary<string, bool>> registry = new Dictionary<Type, Dictionary<string, bool>> (); public bool HasAttribute (object obj, string property) { var type = obj.GetType (); return HasAttribute (type, property); } public bool HasAttribute (Type type, string property) { lock (registry) { Dictionary<string, bool> typeRegistry; if (!registry.TryGetValue (type, out typeRegistry)) { registry [type] = typeRegistry = new Dictionary<string, bool> (); } bool hasAttr; if (!typeRegistry.TryGetValue (property, out hasAttr)) { var propInfo = type.GetProperty (property); hasAttr = propInfo.GetCustomAttributes (typeof(T), true).Length > 0; } return hasAttr; } } } }
using System; using System.Collections.Generic; namespace Toggl.Phoebe.Data { public class AttributeLookupCache<T> where T : Attribute { private readonly Dictionary<Type, Dictionary<string, bool>> registry = new Dictionary<Type, Dictionary<string, bool>> (); public bool HasAttribute (object obj, string property) { var type = obj.GetType (); return HasAttribute (type, property); } public bool HasAttribute (Type type, string property) { Dictionary<string, bool> typeRegistry; if (!registry.TryGetValue (type, out typeRegistry)) { registry [type] = typeRegistry = new Dictionary<string, bool> (); } bool hasAttr; if (!typeRegistry.TryGetValue (property, out hasAttr)) { var propInfo = type.GetProperty (property); hasAttr = propInfo.GetCustomAttributes (typeof(T), true).Length > 0; } return hasAttr; } } }
bsd-3-clause
C#
376d8137596a140f9c99cd9f2964e1858f0b7655
Add mediaItem dictionary helper
martijn00/XamarinMediaManager,mike-rowley/XamarinMediaManager,martijn00/XamarinMediaManager,mike-rowley/XamarinMediaManager
MediaManager/Media/MediaItemExtensions.cs
MediaManager/Media/MediaItemExtensions.cs
using System.Collections.Generic; namespace MediaManager.Media { public static class MediaItemExtensions { public static IDictionary<string, object> ToDictionary(this IMediaItem mediaItem) { var mediaItemDict = new Dictionary<string, object>(); foreach (var item in mediaItem.GetType().GetProperties()) { var value = item.GetValue(mediaItem, null); if (value != null) mediaItemDict.Add(item.Name, value); } return mediaItemDict; } public static string GetTitle(this IMediaItem mediaItem) { if (!string.IsNullOrEmpty(mediaItem.DisplayTitle)) return mediaItem.DisplayTitle; else if (!string.IsNullOrEmpty(mediaItem.Title)) return mediaItem.Title; else return ""; } public static string GetContentTitle(this IMediaItem mediaItem) { if (!string.IsNullOrEmpty(mediaItem.DisplaySubtitle)) return mediaItem.DisplaySubtitle; else if (!string.IsNullOrEmpty(mediaItem.Artist)) return mediaItem.Artist; else if (!string.IsNullOrEmpty(mediaItem.AlbumArtist)) return mediaItem.AlbumArtist; else if (!string.IsNullOrEmpty(mediaItem.Album)) return mediaItem.Album; else return ""; } public static string GetSubText(this IMediaItem mediaItem) { if (!string.IsNullOrEmpty(mediaItem.Album)) return mediaItem.Album; else if (!string.IsNullOrEmpty(mediaItem.Artist)) return mediaItem.Artist; else if (!string.IsNullOrEmpty(mediaItem.AlbumArtist)) return mediaItem.AlbumArtist; else return ""; } } }
namespace MediaManager.Media { public static class MediaItemExtensions { public static string GetTitle(this IMediaItem mediaItem) { if (!string.IsNullOrEmpty(mediaItem.DisplayTitle)) return mediaItem.DisplayTitle; else if (!string.IsNullOrEmpty(mediaItem.Title)) return mediaItem.Title; else return ""; } public static string GetContentTitle(this IMediaItem mediaItem) { if (!string.IsNullOrEmpty(mediaItem.DisplaySubtitle)) return mediaItem.DisplaySubtitle; else if (!string.IsNullOrEmpty(mediaItem.Artist)) return mediaItem.Artist; else if (!string.IsNullOrEmpty(mediaItem.AlbumArtist)) return mediaItem.AlbumArtist; else if (!string.IsNullOrEmpty(mediaItem.Album)) return mediaItem.Album; else return ""; } public static string GetSubText(this IMediaItem mediaItem) { if (!string.IsNullOrEmpty(mediaItem.Album)) return mediaItem.Album; else if (!string.IsNullOrEmpty(mediaItem.Artist)) return mediaItem.Artist; else if (!string.IsNullOrEmpty(mediaItem.AlbumArtist)) return mediaItem.AlbumArtist; else return ""; } } }
mit
C#
c145cffc65b122c3aeebd01cb32f2d8273ea496c
Add missing semi
mixpanel/mixpanel-unity
Mixpanel/Editor/MixpanelSettingsEditor.cs
Mixpanel/Editor/MixpanelSettingsEditor.cs
using UnityEditor; namespace mixpanel.editor { internal class MixpanelSettingsEditor { [SettingsProvider] internal static SettingsProvider CreateCustomSettingsProvider() { // First parameter is the path in the Settings window. // Second parameter is the scope of this setting: it only appears in the Project Settings window. var provider = new SettingsProvider("Project/Mixpanel", SettingsScope.Project); { // Create the SettingsProvider and initialize its drawing (IMGUI) function in place: guiHandler = (searchContext) => { Editor.CreateEditor(MixpanelSettings.Instance).OnInspectorGUI(); }, // Populate the search keywords to enable smart search filtering and label highlighting: keywords = SettingsProvider.GetSearchKeywordsFromSerializedObject(new SerializedObject(MixpanelSettings.Instance)) }; return provider; } } }
using UnityEditor; namespace mixpanel.editor { internal class MixpanelSettingsEditor { [SettingsProvider] internal static SettingsProvider CreateCustomSettingsProvider() { // First parameter is the path in the Settings window. // Second parameter is the scope of this setting: it only appears in the Project Settings window. var provider = new SettingsProvider("Project/Mixpanel", SettingsScope.Project) { // Create the SettingsProvider and initialize its drawing (IMGUI) function in place: guiHandler = (searchContext) => { Editor.CreateEditor(MixpanelSettings.Instance).OnInspectorGUI(); }, // Populate the search keywords to enable smart search filtering and label highlighting: keywords = SettingsProvider.GetSearchKeywordsFromSerializedObject(new SerializedObject(MixpanelSettings.Instance)) }; return provider; } } }
apache-2.0
C#
f95d71470ddc80bbe273d85a239a727571f8d121
Add expression indicating if a post is published
sebastieno/sebastienollivier.fr,sebastieno/sebastienollivier.fr
Blog.Data/Post.cs
Blog.Data/Post.cs
using System; using System.Linq.Expressions; namespace Blog.Data { public class Post { public int Id { get; set; } public string Url { get; set; } public string Title { get; set; } public string Description { get; set; } public string ComputedDescription { get { if (!string.IsNullOrEmpty(this.Description)) { return this.Description; } var description = this.Content.Split(new string[] { "<!-- more -->", "<!--more-->" }, StringSplitOptions.RemoveEmptyEntries); if (description.Length > 0) { return description[0]; } return string.Empty; } } public string Content { get; set; } public DateTime? PublicationDate { get; set; } public int CategoryId { get; set; } public virtual Category Category { get; set; } public static Expression<Func<Post, bool>> IsPublished = post => post.PublicationDate.HasValue && DateTime.Now > post.PublicationDate; } }
using System; namespace Blog.Data { public class Post { public int Id { get; set; } public string Url { get; set; } public string Title { get; set; } public string Description { get; set; } public string ComputedDescription { get { if (!string.IsNullOrEmpty(this.Description)) { return this.Description; } var description = this.Content.Split(new string[] { "<!-- more -->", "<!--more-->" }, StringSplitOptions.RemoveEmptyEntries); if (description.Length > 0) { return description[0]; } return string.Empty; } } public string Content { get; set; } public DateTime? PublicationDate { get; set; } public int CategoryId { get; set; } public virtual Category Category { get; set; } } }
mit
C#
e864f4569fc8667ed51eb1fc10ae626ed71341dc
Change NLogConsumer namespace to Atata
atata-framework/atata,atata-framework/atata,YevgeniyShunevych/Atata,YevgeniyShunevych/Atata
src/Atata/Logging/NLogConsumer.cs
src/Atata/Logging/NLogConsumer.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Atata { public class NLogConsumer : ILogConsumer { private readonly dynamic logger; private readonly Type logEventInfoType; private readonly Dictionary<LogLevel, dynamic> logLevelsMap = new Dictionary<LogLevel, dynamic>(); public NLogConsumer(string loggerName = null) { Type logManagerType = Type.GetType("NLog.LogManager,NLog", true); logger = loggerName != null ? logManagerType.GetMethodWithThrowOnError("GetLogger", typeof(string)).Invoke(null, new[] { loggerName }) : logManagerType.GetMethodWithThrowOnError("GetCurrentClassLogger").Invoke(null, new object[0]); if (logger == null) throw new InvalidOperationException("Failed to create NLog logger."); logEventInfoType = Type.GetType("NLog.NLog,LogEventInfo", true); InitLogLevelsMap(); } private void InitLogLevelsMap() { Type logLevelType = Type.GetType("NLog.LogLevel,NLog", true); PropertyInfo allLevelsProperty = logLevelType.GetPropertyWithThrowOnError("AllLoggingLevels"); IEnumerable allLevels = (IEnumerable)allLevelsProperty.GetValue(null, new object[0]); foreach (LogLevel level in Enum.GetValues(typeof(LogLevel))) { logLevelsMap[level] = allLevels. Cast<dynamic>(). First(x => x.Name == Enum.GetName(typeof(LogLevel), level)); } } public void Log(LogEventInfo eventInfo) { dynamic otherEventInfo = ActivatorEx.CreateInstance(logEventInfoType); otherEventInfo.TimeStamp = eventInfo.Timestamp; otherEventInfo.Level = logLevelsMap[eventInfo.Level]; otherEventInfo.Message = eventInfo.Message; otherEventInfo.Exception = eventInfo.Exception; logger.Log(otherEventInfo); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Atata.Logging { public class NLogConsumer : ILogConsumer { private readonly dynamic logger; private readonly Type logEventInfoType; private readonly Dictionary<LogLevel, dynamic> logLevelsMap = new Dictionary<LogLevel, dynamic>(); public NLogConsumer(string loggerName = null) { Type logManagerType = Type.GetType("NLog.LogManager,NLog", true); logger = loggerName != null ? logManagerType.GetMethodWithThrowOnError("GetLogger", typeof(string)).Invoke(null, new[] { loggerName }) : logManagerType.GetMethodWithThrowOnError("GetCurrentClassLogger").Invoke(null, new object[0]); if (logger == null) throw new InvalidOperationException("Failed to create NLog logger."); logEventInfoType = Type.GetType("NLog.NLog,LogEventInfo", true); InitLogLevelsMap(); } private void InitLogLevelsMap() { Type logLevelType = Type.GetType("NLog.LogLevel,NLog", true); PropertyInfo allLevelsProperty = logLevelType.GetPropertyWithThrowOnError("AllLoggingLevels"); IEnumerable allLevels = (IEnumerable)allLevelsProperty.GetValue(null, new object[0]); foreach (LogLevel level in Enum.GetValues(typeof(LogLevel))) { logLevelsMap[level] = allLevels. Cast<dynamic>(). First(x => x.Name == Enum.GetName(typeof(LogLevel), level)); } } public void Log(LogEventInfo eventInfo) { dynamic otherEventInfo = ActivatorEx.CreateInstance(logEventInfoType); otherEventInfo.TimeStamp = eventInfo.Timestamp; otherEventInfo.Level = logLevelsMap[eventInfo.Level]; otherEventInfo.Message = eventInfo.Message; otherEventInfo.Exception = eventInfo.Exception; logger.Log(otherEventInfo); } } }
apache-2.0
C#
ca9e03bb3a0ed32554ec611b7828b1061d9ef75f
Update ApplicationInsightsMetricTelemeter.cs
tiksn/TIKSN-Framework
TIKSN.Core/Analytics/Telemetry/ApplicationInsightsMetricTelemeter.cs
TIKSN.Core/Analytics/Telemetry/ApplicationInsightsMetricTelemeter.cs
using System; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.ApplicationInsights.DataContracts; namespace TIKSN.Analytics.Telemetry { public class ApplicationInsightsMetricTelemeter : IMetricTelemeter { public Task TrackMetric(string metricName, decimal metricValue) { try { var telemetry = new MetricTelemetry(metricName, (double)metricValue); ApplicationInsightsHelper.TrackMetric(telemetry); } catch (Exception ex) { Debug.WriteLine(ex); } return Task.FromResult<object>(null); } } }
using Microsoft.ApplicationInsights.DataContracts; using System; using System.Diagnostics; using System.Threading.Tasks; namespace TIKSN.Analytics.Telemetry { public class ApplicationInsightsMetricTelemeter : IMetricTelemeter { public Task TrackMetric(string metricName, decimal metricValue) { try { var telemetry = new MetricTelemetry(metricName, (double)metricValue); ApplicationInsightsHelper.TrackMetric(telemetry); } catch (Exception ex) { Debug.WriteLine(ex); } return Task.FromResult<object>(null); } } }
mit
C#
d620b5f148b401c656ad17ac7d3a90706dbb3b40
remove code.
tangxuehua/enode,Aaron-Liu/enode
src/Samples/NoteSample/Program.cs
src/Samples/NoteSample/Program.cs
using System; using System.Reflection; using ECommon.Autofac; using ECommon.Configurations; using ECommon.IoC; using ECommon.JsonNet; using ECommon.Log4Net; using ECommon.Utilities; using ENode.Commanding; using ENode.Configurations; using NoteSample.Commands; using NoteSample.EQueueIntegrations; namespace NoteSample { class Program { static void Main(string[] args) { InitializeENodeFramework(); var commandService = ObjectContainer.Resolve<ICommandService>(); var noteId = ObjectId.GenerateNewStringId(); var command1 = new CreateNoteCommand(noteId, "Sample Title1"); var command2 = new ChangeNoteTitleCommand(noteId, "Sample Title2"); Console.WriteLine(string.Empty); commandService.Execute(command1).Wait(); commandService.Execute(command2).Wait(); Console.WriteLine(string.Empty); Console.WriteLine("Press Enter to exit..."); Console.ReadLine(); } static void InitializeENodeFramework() { var assemblies = new[] { Assembly.GetExecutingAssembly() }; Configuration .Create() .UseAutofac() .RegisterCommonComponents() .UseLog4Net() .UseJsonNet() .CreateENode() .RegisterENodeComponents() .RegisterBusinessComponents(assemblies) .SetProviders() .UseEQueue() .InitializeBusinessAssemblies(assemblies) .StartRetryCommandService() .StartWaitingCommandService() .StartEQueue(); Console.WriteLine(string.Empty); Console.WriteLine("Enode Framework started."); } } }
using System; using System.Reflection; using ECommon.Autofac; using ECommon.Configurations; using ECommon.IoC; using ECommon.JsonNet; using ECommon.Log4Net; using ECommon.Utilities; using ENode.Commanding; using ENode.Configurations; using NoteSample.Commands; using NoteSample.EQueueIntegrations; namespace NoteSample { class Program { static void Main(string[] args) { InitializeENodeFramework(); var commandService = ObjectContainer.Resolve<ICommandService>(); var noteId = ObjectId.GenerateNewStringId(); var command1 = new CreateNoteCommand(noteId, "Sample Title1"); var command2 = new ChangeNoteTitleCommand(noteId, "Sample Title2"); Console.WriteLine(string.Empty); commandService.Execute(command1).Wait(); commandService.Execute(command2).Wait(); Console.WriteLine(string.Empty); Console.WriteLine("Press Enter to exit..."); Console.ReadLine(); } static void InitializeENodeFramework() { var connectionString = "Data Source=(local);Initial Catalog=EventStore;Integrated Security=True;Connect Timeout=30;Min Pool Size=10;Max Pool Size=100"; var assemblies = new[] { Assembly.GetExecutingAssembly() }; Configuration .Create() .UseAutofac() .RegisterCommonComponents() .UseLog4Net() .UseJsonNet() .CreateENode() .RegisterENodeComponents() .UseSqlServerEventStore(connectionString) .RegisterBusinessComponents(assemblies) .SetProviders() .UseEQueue() .InitializeBusinessAssemblies(assemblies) .StartRetryCommandService() .StartWaitingCommandService() .StartEQueue(); Console.WriteLine(string.Empty); Console.WriteLine("Enode Framework started."); } } }
mit
C#
652da44cce4cd78041597f0a71392b1d0e9c835a
Update the docs.
mikeobrien/SimpleConfig,mikeobrien/SimpleConfig
src/SimpleConfig/Configuration.cs
src/SimpleConfig/Configuration.cs
using System.Configuration; using Bender; namespace SimpleConfig { public interface IConfiguration { T Load<T>(string sectionName = null); } public class Configuration : IConfiguration { public T Load<T>(string sectionName = null) { sectionName = sectionName ?? typeof (T).Name.ToCamelCase(); var section = ConfigurationManager.GetSection(sectionName); if (!(section is Section)) throw new ConfigurationErrorsException( "The configuration section '" + sectionName + "' must have a section handler of type '" + typeof(Section).FullName + "'."); if (section == null) throw new ConfigurationErrorsException( "Could not find configuration section '" + sectionName + "'."); return Deserializer.Create(x => x.IgnoreCase()).Deserialize<T>(((Section)section).Element); } } }
using System.Configuration; using Bender; namespace SimpleConfig { public interface IConfiguration { T Load<T>(string sectionName = null); } public class Configuration : IConfiguration { public T Load<T>(string sectionName = null) { return Deserializer.Create(x => x.IgnoreCase()).Deserialize<T>( ((Section)ConfigurationManager.GetSection(sectionName ?? typeof(T).Name.ToCamelCase())).Element); } } }
mit
C#
f5dcc512622d2d4f7d9b5523109352a4550d0a17
Fix for authenticated user
mika-f/Sagitta
Source/Sagitta/Models/ProfileImageUrls.cs
Source/Sagitta/Models/ProfileImageUrls.cs
using Newtonsoft.Json; namespace Sagitta.Models { public class ProfileImageUrls { [JsonProperty("medium")] public string Medium { get; set; } /// <summary> /// 16x16 /// </summary> [JsonProperty("px_16x16")] public string Small { get; set; } [JsonProperty("px_50x50")] private string MediumInternal { get { return Medium; } set { Medium = value; } } [JsonProperty("px_170x170")] public string Large { get; set; } } }
using Newtonsoft.Json; namespace Sagitta.Models { public class ProfileImageUrls { [JsonProperty("medium")] public string Medium { get; set; } } }
mit
C#
45ccea432b287b653dae70f7aed00e43680528bc
Change "UpdatePrompt" subtext for differing major or revision versions
danielchalmers/SteamAccountSwitcher
SteamAccountSwitcher/UpdatePrompt.xaml.cs
SteamAccountSwitcher/UpdatePrompt.xaml.cs
#region using System; using System.Windows; #endregion namespace SteamAccountSwitcher { /// <summary> /// Interaction logic for UpdatePrompt.xaml /// </summary> public partial class UpdatePrompt : Window { public enum UpdateResponse { UpdateNow, RemindLater, RemindNever } public UpdateResponse UserResponse; public UpdatePrompt(Version updateVersion, bool isRequired) { InitializeComponent(); if (!isRequired) { if (updateVersion.Major != AssemblyInfo.GetVersion().Major) { txtUpdateSubMsg.Text = $"A new major release, {AssemblyInfo.GetTitle()} {updateVersion.Major}.{updateVersion.Minor} is now available!"; } else if (updateVersion.Revision != AssemblyInfo.GetVersion().Revision) { txtUpdateSubMsg.Text = $"{AssemblyInfo.GetTitle()} {AssemblyInfo.GetVersionStringFull(updateVersion)} is now available!"; } else { txtUpdateSubMsg.Text = $"{AssemblyInfo.GetTitle()} {AssemblyInfo.GetVersionString(updateVersion)} is now available!"; } txtUpdateSubMsg.Text += "\nDo you want to update to the latest version?"; } else { txtUpdateSubMsg.Text = $"A mandatory update is available.\nPress \"{btnOK.Content}\" to update to the latest version."; } btnNo.Visibility = isRequired ? Visibility.Hidden : Visibility.Visible; btnRemindLater.Visibility = isRequired ? Visibility.Hidden : Visibility.Visible; new ChangelogDownloader().GetChangelog(x => { txtChangelog.Text = x; }); } private void btnRemindLater_Click(object sender, RoutedEventArgs e) { UserResponse = UpdateResponse.RemindLater; DialogResult = true; } private void btnNo_Click(object sender, RoutedEventArgs e) { UserResponse = UpdateResponse.RemindNever; DialogResult = true; } private void btnOK_Click(object sender, RoutedEventArgs e) { UserResponse = UpdateResponse.UpdateNow; DialogResult = true; } } }
#region using System; using System.Windows; #endregion namespace SteamAccountSwitcher { /// <summary> /// Interaction logic for UpdatePrompt.xaml /// </summary> public partial class UpdatePrompt : Window { public enum UpdateResponse { UpdateNow, RemindLater, RemindNever } public UpdateResponse UserResponse; public UpdatePrompt(Version updateVersion, bool isRequired) { InitializeComponent(); txtUpdateSubMsg.Text = !isRequired ? ($"{AssemblyInfo.GetTitle()} {AssemblyInfo.GetVersionString(updateVersion)} is now available!\nDo you want to update to the latest version?") : $"A mandatory update is available.\nPress \"{btnOK.Content}\" to update to the latest version."; btnNo.Visibility = isRequired ? Visibility.Hidden : Visibility.Visible; btnRemindLater.Visibility = isRequired ? Visibility.Hidden : Visibility.Visible; new ChangelogDownloader().GetChangelog(x => { txtChangelog.Text = x; }); } private void btnRemindLater_Click(object sender, RoutedEventArgs e) { UserResponse = UpdateResponse.RemindLater; DialogResult = true; } private void btnNo_Click(object sender, RoutedEventArgs e) { UserResponse = UpdateResponse.RemindNever; DialogResult = true; } private void btnOK_Click(object sender, RoutedEventArgs e) { UserResponse = UpdateResponse.UpdateNow; DialogResult = true; } } }
mit
C#
821544b24b0f6334f6b8945d910d8c7f17a02962
add expriseAt
dotnetcore/CAP,dotnetcore/CAP,ouraspnet/cap,dotnetcore/CAP
src/DotNetCore.CAP/Processor/States/IStateChanger.Default.cs
src/DotNetCore.CAP/Processor/States/IStateChanger.Default.cs
using System; using DotNetCore.CAP.Models; namespace DotNetCore.CAP.Processor.States { public class StateChanger : IStateChanger { public void ChangeState(CapPublishedMessage message, IState state, IStorageTransaction transaction) { var now = DateTime.Now; if (state.ExpiresAfter != null) { message.ExpiresAt = now.Add(state.ExpiresAfter.Value); } else { message.ExpiresAt = null; } message.StatusName = state.Name; state.Apply(message, transaction); transaction.UpdateMessage(message); } public void ChangeState(CapReceivedMessage message, IState state, IStorageTransaction transaction) { var now = DateTime.Now; if (state.ExpiresAfter != null) { message.ExpiresAt = now.Add(state.ExpiresAfter.Value); } else { message.ExpiresAt = null; } message.StatusName = state.Name; state.Apply(message, transaction); transaction.UpdateMessage(message); } } }
using DotNetCore.CAP.Models; namespace DotNetCore.CAP.Processor.States { public class StateChanger : IStateChanger { public void ChangeState(CapPublishedMessage message, IState state, IStorageTransaction transaction) { //var now = DateTime.UtcNow; //if (state.ExpiresAfter != null) //{ // message.ExpiresAt = now.Add(state.ExpiresAfter.Value); //} //else //{ // message.ExpiresAt = null; //} message.StatusName = state.Name; state.Apply(message, transaction); transaction.UpdateMessage(message); } public void ChangeState(CapReceivedMessage message, IState state, IStorageTransaction transaction) { //var now = DateTime.UtcNow; //if (state.ExpiresAfter != null) //{ // job.ExpiresAt = now.Add(state.ExpiresAfter.Value); //} //else //{ // job.ExpiresAt = null; //} message.StatusName = state.Name; state.Apply(message, transaction); transaction.UpdateMessage(message); } } }
mit
C#
3e3ec3de8c23f9cd8c9542f6b685a9c61013a609
update formatting
designsbyjuan/UnityLib
FadeOutPanel.cs
FadeOutPanel.cs
using UnityEngine; using UnityEngine.UI; public class FadeOutPanel : MonoBehaviour { public GameObject fadePanelPrefab; public float fadeTime = 1.5f; // Use this for initialization void Start() {} public void FadePanel() { GameObject fadePanel = (GameObject)Instantiate(fadePanelPrefab); // set clone as child of gameobject fadePanel.transform.SetParent(gameObject.transform, false); Image image = fadePanel.GetComponent<Image>(); // cross fade panel image.CrossFadeAlpha(0, fadeTime, false); // destroy clone when fade has ended Destroy(fadePanel, fadeTime); } }
using UnityEngine; using UnityEngine.UI; public class FadeOutPanel : MonoBehaviour { public GameObject fadePanelPrefab; public float fadeTime = 1.5f; // Use this for initialization void Start() {} public void FadePanel() { GameObject fadePanel = (GameObject)Instantiate(fadePanelPrefab); // set clone as child of gameobject fadePanel.transform.SetParent(gameObject.transform, false); Image image = fadePanel.GetComponent<Image>(); // cross fade panel image.CrossFadeAlpha(0, fadeTime, false); // destroy clone when fade has ended Destroy(fadePanel, fadeTime); } }
mit
C#
686f0b9ceedceb8ca255ccc6e7ae7fbaf80f239b
Fix process of requesting access to a room
RightpointLabs/conference-room,RightpointLabs/conference-room,jorupp/conference-room,jorupp/conference-room,RightpointLabs/conference-room,RightpointLabs/conference-room,jorupp/conference-room,jorupp/conference-room
RightpointLabs.ConferenceRoom.Services/Controllers/BaseController.cs
RightpointLabs.ConferenceRoom.Services/Controllers/BaseController.cs
using log4net; using RightpointLabs.ConferenceRoom.Services.Attributes; using System.Net.Http; using System.ServiceModel.Channels; using System.Web; using System.Web.Http; namespace RightpointLabs.ConferenceRoom.Services.Controllers { /// <summary> /// Operations dealing with client log messages /// </summary> [ErrorHandler] public abstract class BaseController : ApiController { protected BaseController(ILog log) { this.Log = log; } protected internal ILog Log { get; private set; } protected string GetClientIp(HttpRequestMessage request = null) { request = request ?? Request; // from https://trikks.wordpress.com/2013/06/27/getting-the-client-ip-via-asp-net-web-api/ if (request.Properties.ContainsKey("MS_HttpContext")) { return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress; } else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name)) { RemoteEndpointMessageProperty prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name]; return prop.Address; } else if (HttpContext.Current != null) { return HttpContext.Current.Request.UserHostAddress; } else { return null; } } } }
using log4net; using RightpointLabs.ConferenceRoom.Services.Attributes; using System.Net.Http; using System.ServiceModel.Channels; using System.Web; using System.Web.Http; namespace RightpointLabs.ConferenceRoom.Services.Controllers { /// <summary> /// Operations dealing with client log messages /// </summary> [ErrorHandler] public abstract class BaseController : ApiController { protected BaseController(ILog log) { this.Log = log; } protected internal ILog Log { get; private set; } protected static string GetClientIp(HttpRequestMessage request = null) { // from https://trikks.wordpress.com/2013/06/27/getting-the-client-ip-via-asp-net-web-api/ if (request.Properties.ContainsKey("MS_HttpContext")) { return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress; } else if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name)) { RemoteEndpointMessageProperty prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name]; return prop.Address; } else if (HttpContext.Current != null) { return HttpContext.Current.Request.UserHostAddress; } else { return null; } } } }
mit
C#
0df770b1c46c1e0ffb86b7cee24e70cec95d1080
fix datagrid xmlns
wieslawsoltes/Perspex,SuperJMN/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex,akrisiun/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia
src/Avalonia.Controls.DataGrid/Properties/AssemblyInfo.cs
src/Avalonia.Controls.DataGrid/Properties/AssemblyInfo.cs
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Reflection; using System.Runtime.CompilerServices; using Avalonia.Metadata; [assembly: InternalsVisibleTo("Avalonia.Controls.UnitTests")] [assembly: InternalsVisibleTo("Avalonia.DesignerSupport")] [assembly: XmlnsDefinition("https://github.com/avaloniaui", "Avalonia.Controls")] [assembly: XmlnsDefinition("https://github.com/avaloniaui", "Avalonia.Controls.Collections")] [assembly: XmlnsDefinition("https://github.com/avaloniaui", "Avalonia.Controls.Primitives")]
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Reflection; using System.Runtime.CompilerServices; using Avalonia.Metadata; [assembly: InternalsVisibleTo("Avalonia.Controls.UnitTests")] [assembly: InternalsVisibleTo("Avalonia.DesignerSupport")] [assembly: XmlnsDefinition("https://github.com/avaloniaui", "Avalonia.Controls")]
mit
C#
d67ff529b74e4d6c9716279f2da1cca9d69bd145
Make ScalarTemplatePropertyValueDictionary a dictionary
messagetemplates/messagetemplates-csharp,messagetemplates/messagetemplates-csharp
src/MessageTemplates/Core/ScalarTemplatePropertyValueDictionary.cs
src/MessageTemplates/Core/ScalarTemplatePropertyValueDictionary.cs
using System; using System.Collections; using System.Collections.Generic; using MessageTemplates.Structure; using System.Linq; namespace MessageTemplates.Core { /// <summary> /// /// </summary> public class ScalarTemplatePropertyValueDictionary : IEnumerable<KeyValuePair<ScalarValue, TemplatePropertyValue>> { private IDictionary<ScalarValue, TemplatePropertyValue> elements; /// <summary> /// /// </summary> /// <param name="elements"></param> public ScalarTemplatePropertyValueDictionary( IEnumerable<KeyValuePair<ScalarValue, TemplatePropertyValue>> elements) { this.elements = elements.ToDictionary(e => e.Key, e => e.Value); } /// <summary> /// /// </summary> /// <returns></returns> public IEnumerator<KeyValuePair<ScalarValue, TemplatePropertyValue>> GetEnumerator() { return elements.GetEnumerator(); } /// <summary> /// /// </summary> /// <returns></returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
using System; using System.Collections; using System.Collections.Generic; using MessageTemplates.Structure; namespace MessageTemplates.Core { /// <summary> /// /// </summary> public class ScalarTemplatePropertyValueDictionary : IEnumerable<KeyValuePair<ScalarValue, TemplatePropertyValue>> { private IEnumerable<KeyValuePair<ScalarValue, TemplatePropertyValue>> elements; /// <summary> /// /// </summary> /// <param name="elements"></param> public ScalarTemplatePropertyValueDictionary(IEnumerable<KeyValuePair<ScalarValue, TemplatePropertyValue>> elements) { this.elements = elements; } /// <summary> /// /// </summary> /// <returns></returns> public IEnumerator<KeyValuePair<ScalarValue, TemplatePropertyValue>> GetEnumerator() { throw new NotImplementedException(); } /// <summary> /// /// </summary> /// <returns></returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
apache-2.0
C#
e827d120113b92a9ad19fb62d921a9afc8057fdb
Fix game inline query result
MrRoundRobin/telegram.bot,TelegramBots/telegram.bot,AndyDingo/telegram.bot
src/Telegram.Bot/Types/InlineQueryResults/InlineQueryResultGame.cs
src/Telegram.Bot/Types/InlineQueryResults/InlineQueryResultGame.cs
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Telegram.Bot.Types.InlineQueryResults { /// <summary> /// Represents a <see cref="Game"/>. /// </summary> /// <seealso cref="InlineQueryResult" /> [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] public class InlineQueryResultGame : InlineQueryResult { /// <summary> /// Initializes a new inline query result /// </summary> public InlineQueryResultGame() { Type = InlineQueryResultType.Game; } /// <summary> /// Short name of the game. /// </summary> [JsonProperty(Required = Required.Always)] public string GameShortName { get; set; } } }
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System.ComponentModel; using Telegram.Bot.Types.InputMessageContents; namespace Telegram.Bot.Types.InlineQueryResults { /// <summary> /// Represents a <see cref="Game"/>. /// </summary> /// <seealso cref="InlineQueryResultNew" /> [JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] public class InlineQueryResultGame : InlineQueryResult { /// <summary> /// Initializes a new inline query result /// </summary> public InlineQueryResultGame() { Type = InlineQueryResultType.Game; } /// <summary> /// Short name of the game. /// </summary> [JsonProperty(Required = Required.Always)] public string GameShortName { get; set; } #pragma warning disable 1591 [JsonIgnore] [EditorBrowsable(EditorBrowsableState.Never)] public new string Title { get; set; } [JsonIgnore] [EditorBrowsable(EditorBrowsableState.Never)] public new InputMessageContent InputMessageContent { get; set; } #pragma warning restore 1591 } }
mit
C#
fa03a47e2bfd4a42e4a6230708db1e628ebf0d25
Clear up ItemPageViewModel.cs
wangjun/windows-app,wangjun/windows-app
wallabag/wallabag.Shared/ViewModel/ItemPageViewModel.cs
wallabag/wallabag.Shared/ViewModel/ItemPageViewModel.cs
using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Ioc; using Windows.ApplicationModel.DataTransfer; using Windows.UI.Xaml.Media; namespace wallabag.ViewModel { public class ItemPageViewModel : ViewModelBase { private ItemViewModel _Item; public ItemViewModel Item { get { return _Item; } set { Set(() => Item, ref _Item, value); } } public SolidColorBrush Background { get { return new SettingsViewModel().Background; } } public SolidColorBrush textColor { get { return new SettingsViewModel().textColor; } } public RelayCommand shareCommand { get; private set; } [PreferredConstructor] public ItemPageViewModel() { shareCommand = new RelayCommand(() => DataTransferManager.ShowShareUI()); } public ItemPageViewModel(ItemViewModel item) { shareCommand = new RelayCommand(() => DataTransferManager.ShowShareUI()); Item = item; } } }
using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Ioc; using Windows.ApplicationModel.DataTransfer; using Windows.UI.Xaml.Media; namespace wallabag.ViewModel { public class ItemPageViewModel : ViewModelBase { private ItemViewModel _Item; public ItemViewModel Item { get { return _Item; } set { Set(() => Item, ref _Item, value); } } public SolidColorBrush Background { get { return new SettingsViewModel().Background; } } public SolidColorBrush textColor { get { return new SettingsViewModel().textColor; } } public RelayCommand shareCommand { get; private set; } private void share() { DataTransferManager.ShowShareUI(); } [PreferredConstructor] public ItemPageViewModel() { shareCommand = new RelayCommand(() => share()); } public ItemPageViewModel(ItemViewModel item) { shareCommand = new RelayCommand(() => share()); Item = item; } } }
mit
C#
9f6535de2c7e21e17348fb550478c146efdd7b3f
Update to use CSLA configuration
rockfordlhotka/csla,JasonBock/csla,MarimerLLC/csla,JasonBock/csla,MarimerLLC/csla,rockfordlhotka/csla,MarimerLLC/csla,JasonBock/csla,rockfordlhotka/csla
Samples/ProjectTracker/ProjectTracker.AppServerCore/Startup.cs
Samples/ProjectTracker/ProjectTracker.AppServerCore/Startup.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Csla.Configuration; namespace ProjectTracker.AppServerCore { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddCsla(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); app.UseCsla(); ConfigurationManager.AppSettings["DalManagerType"] = "ProjectTracker.DalMock.DalManager,ProjectTracker.DalMock"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace ProjectTracker.AppServerCore { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); Csla.Configuration.ConfigurationManager.AppSettings["DalManagerType"] = "ProjectTracker.DalMock.DalManager,ProjectTracker.DalMock"; } } }
mit
C#
6aa592f7c88177076d05888eb33d16d0874063d8
Implement AddressSpaceComplianceTestTool - added top level exception handling.
mpostol/OPC-UA-OOI
SemanticDataSolution/AddressSpaceComplianceTestTool/Program.cs
SemanticDataSolution/AddressSpaceComplianceTestTool/Program.cs
 using System; using System.IO; namespace UAOOI.SemanticData.AddressSpaceTestTool { class Program { internal static void Main(string[] args) { try { FileInfo _fileToRead = GetFileToRead(args); ValidateFile(_fileToRead); } catch (Exception ex) { Console.WriteLine(String.Format("Program stoped by the exception: {0}", ex.Message)); } Console.Write("Press ENter to close this window......."); Console.Read(); } internal static void ValidateFile(FileInfo _fileToRead) { throw new NotImplementedException(); } internal static FileInfo GetFileToRead(string[] args) { throw new NotImplementedException(); } } }
 using System; using System.IO; namespace UAOOI.SemanticData.AddressSpaceTestTool { class Program { internal static void Main(string[] args) { FileInfo _fileToRead = GetFileToRead(args); ValidateFile(_fileToRead); } internal static void ValidateFile(FileInfo _fileToRead) { throw new NotImplementedException(); } internal static FileInfo GetFileToRead(string[] args) { throw new NotImplementedException(); } } }
mit
C#
1e5f40919f5efa1224a0fd71aad2278721032cd3
Fix VS package template assembly version.
rsdn/nitra,rsdn/nitra
Nitra.LanguageCompiler/Templates/XXLanguageFullNameXXVsPackage/Properties/AssemblyInfo.cs
Nitra.LanguageCompiler/Templates/XXLanguageFullNameXXVsPackage/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: Microsoft.VisualStudio.Shell.ProvideCodeBase(CodeBase = @"$PackageFolder$\XXLanguageFullNameXXVsPackage.dll")] // 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("XXLanguageFullNameXXVsPackage")] [assembly: AssemblyDescription("XXDescriptionXX")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("XXCompanyXX")] [assembly: AssemblyProduct("XXLanguageFullNameXXVsPackage")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] [assembly: CLSCompliant(false)] [assembly: NeutralResourcesLanguage("en-US")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1af3336c-f187-499f-8cc7-e472ed6cc33c")] // 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("XXPackageVersionXX")] [assembly: AssemblyFileVersion("XXPackageVersionXX")]
using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: Microsoft.VisualStudio.Shell.ProvideCodeBase(CodeBase = @"$PackageFolder$\XXLanguageFullNameXXVsPackage.dll")] // 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("XXLanguageFullNameXXVsPackage")] [assembly: AssemblyDescription("XXDescriptionXX")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("XXCompanyXX")] [assembly: AssemblyProduct("XXLanguageFullNameXXVsPackage")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] [assembly: CLSCompliant(false)] [assembly: NeutralResourcesLanguage("en-US")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1af3336c-f187-499f-8cc7-e472ed6cc33c")] // 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")]
apache-2.0
C#
b82a591e40548185e47efc173601d10f6b8da86f
Update ExceptionlessMetricTelemeter.cs
tiksn/TIKSN-Framework
TIKSN.Core/Analytics/Telemetry/ExceptionlessMetricTelemeter.cs
TIKSN.Core/Analytics/Telemetry/ExceptionlessMetricTelemeter.cs
using System; using System.Diagnostics; using System.Threading.Tasks; using Exceptionless; namespace TIKSN.Analytics.Telemetry { public class ExceptionlessMetricTelemeter : ExceptionlessTelemeterBase, IMetricTelemeter { public async Task TrackMetric(string metricName, decimal metricValue) { try { ExceptionlessClient.Default.CreateFeatureUsage(metricName).SetValue(metricValue).Submit(); } catch (Exception ex) { Debug.WriteLine(ex); } } } }
using Exceptionless; using System; using System.Diagnostics; using System.Threading.Tasks; namespace TIKSN.Analytics.Telemetry { public class ExceptionlessMetricTelemeter : ExceptionlessTelemeterBase, IMetricTelemeter { public async Task TrackMetric(string metricName, decimal metricValue) { try { ExceptionlessClient.Default.CreateFeatureUsage(metricName).SetValue(metricValue).Submit(); } catch (Exception ex) { Debug.WriteLine(ex); } } } }
mit
C#
3113275dea34dfe04f89335ac68d30748e34a3a8
Change to TileLayer as sealed.
JKennedy24/Xamarin.Forms.GoogleMaps,JKennedy24/Xamarin.Forms.GoogleMaps,quesera2/Xamarin.Forms.GoogleMaps,amay077/Xamarin.Forms.GoogleMaps
Xamarin.Forms.GoogleMaps/Xamarin.Forms.GoogleMaps/TileLayer.cs
Xamarin.Forms.GoogleMaps/Xamarin.Forms.GoogleMaps/TileLayer.cs
using System; using System.Threading.Tasks; namespace Xamarin.Forms.GoogleMaps { public sealed class TileLayer { // For URI specific SyncTileLayer private Func<int, int, int, Uri> _makeTileUri = null; internal Func<int, int, int, Uri> MakeTileUri { get { return _makeTileUri; } } // For Image specific SyncTileLayer private Func<int, int, int, byte[]> _tileImageSync = null; internal Func<int, int, int, byte[]> TileImageSync { get { return _tileImageSync; } } // For Image specific AsyncTileLayer private Func<int, int, int, Task<byte[]>> _tileImageAsync = null; internal Func<int, int, int, Task<byte[]>> TileImageAsync { get { return _tileImageAsync; } } private int _tileSize = 256; public int TileSize { get { return _tileSize; } } public object Tag { get; set; } internal object Id { get; set; } private TileLayer(Func<int, int, int, Uri> makeTileUri, int tileSize = 256) { _makeTileUri = makeTileUri; _tileSize = tileSize; } private TileLayer(Func<int, int, int, byte[]> tileImageSync, int tileSize = 256) { _tileImageSync = tileImageSync; _tileSize = tileSize; } private TileLayer(Func<int, int, int, Task<byte[]>> tileImageAsync, int tileSize = 256) { _tileImageAsync = tileImageAsync; _tileSize = tileSize; } public static TileLayer FromTileUri(Func<int, int, int, Uri> makeTileUri, int tileSize = 256) { return new TileLayer(makeTileUri, tileSize); } public static TileLayer FromSyncImage(Func<int, int, int, byte[]> tileImageSync, int tileSize = 256) { return new TileLayer(tileImageSync, tileSize); } public static TileLayer FromASyncImage(Func<int, int, int, Task<byte[]>> tileImageAsync, int tileSize = 256) { return new TileLayer(tileImageAsync, tileSize); } } }
using System; using System.Threading.Tasks; namespace Xamarin.Forms.GoogleMaps { public class TileLayer { // For URI specific SyncTileLayer private Func<int, int, int, Uri> _makeTileUri = null; internal Func<int, int, int, Uri> MakeTileUri { get { return _makeTileUri; } } // For Image specific SyncTileLayer private Func<int, int, int, byte[]> _tileImageSync = null; internal Func<int, int, int, byte[]> TileImageSync { get { return _tileImageSync; } } // For Image specific AsyncTileLayer private Func<int, int, int, Task<byte[]>> _tileImageAsync = null; internal Func<int, int, int, Task<byte[]>> TileImageAsync { get { return _tileImageAsync; } } private int _tileSize = 256; public int TileSize { get { return _tileSize; } } public object Tag { get; set; } internal object Id { get; set; } private TileLayer(Func<int, int, int, Uri> makeTileUri, int tileSize = 256) { _makeTileUri = makeTileUri; _tileSize = tileSize; } private TileLayer(Func<int, int, int, byte[]> tileImageSync, int tileSize = 256) { _tileImageSync = tileImageSync; _tileSize = tileSize; } private TileLayer(Func<int, int, int, Task<byte[]>> tileImageAsync, int tileSize = 256) { _tileImageAsync = tileImageAsync; _tileSize = tileSize; } public static TileLayer FromTileUri(Func<int, int, int, Uri> makeTileUri, int tileSize = 256) { return new TileLayer(makeTileUri, tileSize); } public static TileLayer FromSyncImage(Func<int, int, int, byte[]> tileImageSync, int tileSize = 256) { return new TileLayer(tileImageSync, tileSize); } public static TileLayer FromASyncImage(Func<int, int, int, Task<byte[]>> tileImageAsync, int tileSize = 256) { return new TileLayer(tileImageAsync, tileSize); } } }
mit
C#
aa4dd3ec8c2d37d5a27e4701af7a95905e3cb8ba
fix awaiting to get current user, because not waiting a result and not throwing exception
aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template
aspnet-core/src/AbpCompanyName.AbpProjectName.Application/AbpProjectNameAppServiceBase.cs
aspnet-core/src/AbpCompanyName.AbpProjectName.Application/AbpProjectNameAppServiceBase.cs
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Abp.Application.Services; using Abp.IdentityFramework; using Abp.Runtime.Session; using AbpCompanyName.AbpProjectName.Authorization.Users; using AbpCompanyName.AbpProjectName.MultiTenancy; namespace AbpCompanyName.AbpProjectName { /// <summary> /// Derive your application services from this class. /// </summary> public abstract class AbpProjectNameAppServiceBase : ApplicationService { public TenantManager TenantManager { get; set; } public UserManager UserManager { get; set; } protected AbpProjectNameAppServiceBase() { LocalizationSourceName = AbpProjectNameConsts.LocalizationSourceName; } protected virtual async Task<User> GetCurrentUserAsync() { var user = await UserManager.FindByIdAsync(AbpSession.GetUserId().ToString()); if (user == null) { throw new Exception("There is no current user!"); } return user; } protected virtual Task<Tenant> GetCurrentTenantAsync() { return TenantManager.GetByIdAsync(AbpSession.GetTenantId()); } protected virtual void CheckErrors(IdentityResult identityResult) { identityResult.CheckErrors(LocalizationManager); } } }
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Abp.Application.Services; using Abp.IdentityFramework; using Abp.Runtime.Session; using AbpCompanyName.AbpProjectName.Authorization.Users; using AbpCompanyName.AbpProjectName.MultiTenancy; namespace AbpCompanyName.AbpProjectName { /// <summary> /// Derive your application services from this class. /// </summary> public abstract class AbpProjectNameAppServiceBase : ApplicationService { public TenantManager TenantManager { get; set; } public UserManager UserManager { get; set; } protected AbpProjectNameAppServiceBase() { LocalizationSourceName = AbpProjectNameConsts.LocalizationSourceName; } protected virtual Task<User> GetCurrentUserAsync() { var user = UserManager.FindByIdAsync(AbpSession.GetUserId().ToString()); if (user == null) { throw new Exception("There is no current user!"); } return user; } protected virtual Task<Tenant> GetCurrentTenantAsync() { return TenantManager.GetByIdAsync(AbpSession.GetTenantId()); } protected virtual void CheckErrors(IdentityResult identityResult) { identityResult.CheckErrors(LocalizationManager); } } }
mit
C#
5b5bb9758e5d9f7e4d5679ee2fa30a2aadcb2452
Update ResourceBackupStatus.cs
AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell
src/ResourceManager/RecoveryServices/Commands.RecoveryServices.Backup.Models/CommonModels/ResourceBackupStatus.cs
src/ResourceManager/RecoveryServices/Commands.RecoveryServices.Backup.Models/CommonModels/ResourceBackupStatus.cs
// ---------------------------------------------------------------------------------- // // 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 System; namespace Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.Models { /// <summary> /// Backup status of a resource. /// </summary> public class ResourceBackupStatus { /// <summary> /// The Resource Name. /// </summary> public string Name { get; set; } /// <summary> /// The Resource Group Name. /// </summary> public string ResourceGroupName { get; set; } /// <summary> /// If the resource is protected by some vault in the subscription, this contains the resource ID of that vault. /// </summary> public string VaultId { get; set; } /// <summary> /// Specifies whether the resource is protected by some vault in the subscription. /// </summary> public bool BackedUp { get; set; } public ResourceBackupStatus(string name, string resourceGroupName, string vaultId, bool backedUp) { if (backedUp && string.IsNullOrEmpty(vaultId) || !backedUp && !string.IsNullOrEmpty(vaultId)) { throw new ArgumentException($"Inconsistent parameters specified. backedUp: {backedUp} and vaultId: {vaultId}."); } Name = name; ResourceGroupName = resourceGroupName; VaultId = vaultId; BackedUp = backedUp; } } }
using System; namespace Microsoft.Azure.Commands.RecoveryServices.Backup.Cmdlets.Models { /// <summary> /// Backup status of a resource. /// </summary> public class ResourceBackupStatus { /// <summary> /// The Resource Name. /// </summary> public string Name { get; set; } /// <summary> /// The Resource Group Name. /// </summary> public string ResourceGroupName { get; set; } /// <summary> /// If the resource is protected by some vault in the subscription, this contains the resource ID of that vault. /// </summary> public string VaultId { get; set; } /// <summary> /// Specifies whether the resource is protected by some vault in the subscription. /// </summary> public bool BackedUp { get; set; } public ResourceBackupStatus(string name, string resourceGroupName, string vaultId, bool backedUp) { if (backedUp && string.IsNullOrEmpty(vaultId) || !backedUp && !string.IsNullOrEmpty(vaultId)) { throw new ArgumentException($"Inconsistent parameters specified. backedUp: {backedUp} and vaultId: {vaultId}."); } Name = name; ResourceGroupName = resourceGroupName; VaultId = vaultId; BackedUp = backedUp; } } }
apache-2.0
C#