conflict_resolution
stringlengths
27
16k
<<<<<<< // Special case for home page if (SPContext.Current.ListItem != null && web.RootFolder.WelcomePage == SPContext.Current.ListItem.Url) { return new Uri(label.TopWebUrl.ToString()); } ======= >>>>>>> <<<<<<< return new Uri( Variations.GetPeerUrl(web, currentUrl.AbsolutePath, label.Title), UriKind.Relative); ======= var peerPageUri = new Uri(Variations.GetPeerUrl(SPContext.Current.Web, currentUrl.AbsolutePath, label.Title), UriKind.Relative); // Special case for home page if (SPContext.Current.ListItem != null && SPContext.Current.Web.RootFolder.WelcomePage == SPContext.Current.ListItem.Url) { var peerHomePageUrl = Regex.Replace(peerPageUri.OriginalString, @"\/Pages\/.*", string.Empty); peerPageUri = new Uri(peerHomePageUrl, UriKind.Relative); } return peerPageUri; >>>>>>> var peerPageUri = new Uri(Variations.GetPeerUrl(web, currentUrl.AbsolutePath, label.Title), UriKind.Relative); // Special case for home page if (SPContext.Current.ListItem != null && web.RootFolder.WelcomePage == SPContext.Current.ListItem.Url) { var peerHomePageUrl = Regex.Replace(peerPageUri.OriginalString, @"\/Pages\/.*", string.Empty); peerPageUri = new Uri(peerHomePageUrl, UriKind.Relative); } return peerPageUri;
<<<<<<< /* * Copyright (C) 2007, Robin Rosenberg <[email protected]> * Copyright (C) 2008, Shawn O. Pearce <[email protected]> * Copyright (C) 2008, Kevin Thompson <[email protected]> * Copyright (C) 2009, Henon <[email protected]> * * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * - Neither the name of the Git Development Community nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.IO; using GitSharp.Transport; namespace GitSharp { public class PackIndexWriterV1 : PackIndexWriter { public static bool CanStore(PackedObjectInfo objectInfo) { // We are limited to 4 GB per pack as offset is 32 bit unsigned int. // return objectInfo.Offset.UnsignedRightShift(1) < int.MaxValue; } public PackIndexWriterV1(Stream output) : base(output) { } internal override void WriteInternal() { WriteFanOutTable(); foreach (PackedObjectInfo oe in entries) { if (!CanStore(oe)) { throw new IOException("Pack too large for index version 1"); } _stream.Write((int)oe.Offset); _stream.Write(oe); } WriteChecksumFooter(); } } } ======= using System; using System.Collections.Generic; using System.Linq; using System.Text; using GitSharp.Transport; using System.IO; using GitSharp.Util; namespace GitSharp { public class PackIndexWriterV1 : PackIndexWriter { public static bool CanStore(PackedObjectInfo objectInfo) { // We are limited to 4 GB per pack as offset is 32 bit unsigned int. // return objectInfo.Offset.UnsignedRightShift(1) < int.MaxValue; } public PackIndexWriterV1(Stream output) : base(output) { } internal override void WriteInternal() { WriteFanOutTable(); foreach (PackedObjectInfo oe in entries) { if (!CanStore(oe)) throw new IOException("Pack too large for index version 1"); NB.encodeInt32(tmp, 0, (int)oe.Offset); oe.copyRawTo(tmp, 4); _stream.Write(tmp, 0, tmp.Length); } WriteChecksumFooter(); } } } >>>>>>> /* * Copyright (C) 2007, Robin Rosenberg <[email protected]> * Copyright (C) 2008, Shawn O. Pearce <[email protected]> * Copyright (C) 2008, Kevin Thompson <[email protected]> * Copyright (C) 2009, Henon <[email protected]> * * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * - Neither the name of the Git Development Community nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.IO; using GitSharp.Transport; namespace GitSharp { public class PackIndexWriterV1 : PackIndexWriter { public static bool CanStore(PackedObjectInfo objectInfo) { // We are limited to 4 GB per pack as offset is 32 bit unsigned int. // return objectInfo.Offset.UnsignedRightShift(1) < int.MaxValue; } public PackIndexWriterV1(Stream output) : base(output) { } internal override void WriteInternal() { WriteFanOutTable(); foreach (PackedObjectInfo oe in entries) { if (!CanStore(oe)) { throw new IOException("Pack too large for index version 1"); } NB.encodeInt32(tmp, 0, (int)oe.Offset); oe.copyRawTo(tmp, 4); _stream.Write(tmp, 0, tmp.Length); } WriteChecksumFooter(); } } }
<<<<<<< using Microsoft.Toolkit.Uwp.UI.Animations; ======= using Microsoft.Toolkit.Uwp.UI.Brushes; >>>>>>> using Microsoft.Toolkit.Uwp.UI.Animations; using Microsoft.Toolkit.Uwp.UI.Brushes; <<<<<<< // Search in Microsoft.Toolkit.Uwp.UI.Animations var animationsProxyType = EasingType.Default; assembly = animationsProxyType.GetType().GetTypeInfo().Assembly; foreach (var typeInfo in assembly.ExportedTypes) { if (typeInfo.Name == typeName) { return typeInfo; } } ======= // Search in Microsoft.Toolkit.Uwp.UI var uiProxyType = ImageBlendMode.Multiply; assembly = uiProxyType.GetType().GetTypeInfo().Assembly; foreach (var typeInfo in assembly.ExportedTypes) { if (typeInfo.Name == typeName) { return typeInfo; } } >>>>>>> // Search in Microsoft.Toolkit.Uwp.UI.Animations var animationsProxyType = EasingType.Default; assembly = animationsProxyType.GetType().GetTypeInfo().Assembly; foreach (var typeInfo in assembly.ExportedTypes) { if (typeInfo.Name == typeName) { return typeInfo; } } // Search in Microsoft.Toolkit.Uwp.UI var uiProxyType = ImageBlendMode.Multiply; assembly = uiProxyType.GetType().GetTypeInfo().Assembly; foreach (var typeInfo in assembly.ExportedTypes) { if (typeInfo.Name == typeName) { return typeInfo; } }
<<<<<<< return File.Exists(fileSystemInfo.FullName); } public static FileSystemInfo[] ListFiles(this FileSystemInfo fileInfo) { if (fileInfo.IsFile()) { return null; } return Directory.GetFileSystemEntries(fileInfo.FullName).Select(x => new FileInfo(x)).ToArray(); } public static bool Mkdirs(this DirectoryInfo directoryInfo) { if (directoryInfo.Exists) { return true; } directoryInfo.Parent.Mkdirs(); directoryInfo.Create(); return true; } ======= return fileSystemInfo is FileInfo; } >>>>>>> return fileSystemInfo is FileInfo; } public static FileSystemInfo[] ListFiles(this FileSystemInfo fileInfo) { if (fileInfo.IsFile()) { return null; } return Directory.GetFileSystemEntries(fileInfo.FullName).Select(x => new FileInfo(x)).ToArray(); } public static bool Mkdirs(this DirectoryInfo directoryInfo) { if (directoryInfo.Exists) { return true; } directoryInfo.Parent.Mkdirs(); directoryInfo.Create(); return true; }
<<<<<<< ======= o.Dispose(); >>>>>>> <<<<<<< ======= o.Dispose(); >>>>>>>
<<<<<<< using System.IO; using GitSharp.RevWalk; using GitSharp.Transport; using NUnit.Framework; ======= >>>>>>> <<<<<<< [Test] public void test001_Write() { byte[] bundle = makeBundle("refs/heads/firstcommit", "42e4e7c5e507e113ebbb7801b16b52cf867b7ce1", null); Repository newRepo = createNewEmptyRepo(); FetchResult fetchResult = fetchFromBundle(newRepo, bundle); Ref advertisedRef = fetchResult.GetAdvertisedRef("refs/heads/firstcommit"); Assert.AreEqual("42e4e7c5e507e113ebbb7801b16b52cf867b7ce1", advertisedRef.ObjectId.Name); Assert.AreEqual("42e4e7c5e507e113ebbb7801b16b52cf867b7ce1", newRepo.Resolve("refs/heads/firstcommit").Name); } #if false /** * Incremental bundle test * * @throws Exception */ public void testWrite1() throws Exception { byte[] bundle; // Create a small bundle, an early commit bundle = makeBundle("refs/heads/aa", db.resolve("a").name(), null); // Then we clone a new repo from that bundle and do a simple test. This // makes sure // we could read the bundle we created. Repository newRepo = createNewEmptyRepo(); FetchResult fetchResult = fetchFromBundle(newRepo, bundle); Ref advertisedRef = fetchResult.getAdvertisedRef("refs/heads/aa"); assertEquals(db.resolve("a").name(), advertisedRef.getObjectId().name()); assertEquals(db.resolve("a").name(), newRepo.resolve("refs/heads/aa") .name()); assertNull(newRepo.resolve("refs/heads/a")); // Next an incremental bundle bundle = makeBundle("refs/heads/cc", db.resolve("c").name(), new RevWalk(db).parseCommit(db.resolve("a").toObjectId())); fetchResult = fetchFromBundle(newRepo, bundle); advertisedRef = fetchResult.getAdvertisedRef("refs/heads/cc"); assertEquals(db.resolve("c").name(), advertisedRef.getObjectId().name()); assertEquals(db.resolve("c").name(), newRepo.resolve("refs/heads/cc") .name()); assertNull(newRepo.resolve("refs/heads/c")); assertNull(newRepo.resolve("refs/heads/a")); // still unknown try { // Check that we actually needed the first bundle Repository newRepo2 = createNewEmptyRepo(); fetchResult = fetchFromBundle(newRepo2, bundle); fail("We should not be able to fetch from bundle with prerequisites that are not fulfilled"); } catch (MissingBundlePrerequisiteException e) { assertTrue(e.getMessage() .indexOf(db.resolve("refs/heads/a").name()) >= 0); } } #endif private FetchResult fetchFromBundle(Repository newRepo, byte[] bundle) { URIish uri = new URIish("in-memory://"); MemoryStream i = new MemoryStream(bundle); RefSpec rs = new RefSpec("refs/heads/*:refs/heads/*"); List<RefSpec> refs = new List<RefSpec>{rs}; return new TransportBundleStream(newRepo, uri, i).fetch(new NullProgressMonitor(), refs); } private byte[] makeBundle(string name, string anObjectToInclude, RevCommit assume) { BundleWriter bw; bw = new BundleWriter(db, new NullProgressMonitor()); bw.include(name, ObjectId.FromString(anObjectToInclude)); if (assume != null) bw.assume(assume); MemoryStream o = new MemoryStream(); bw.writeBundle(o); return o.ToArray(); } ======= #region Test methods #region testWrite0 [Test] public void testWrite0() { // Create a tiny bundle, (well one of) the first commits only byte[] bundle = makeBundle("refs/heads/firstcommit", "42e4e7c5e507e113ebbb7801b16b52cf867b7ce1", null); // Then we clone a new repo from that bundle and do a simple test. This // makes sure // we could read the bundle we created. Repository newRepo = createNewEmptyRepo(); FetchResult fetchResult = fetchFromBundle(newRepo, bundle); Ref advertisedRef = fetchResult.GetAdvertisedRef("refs/heads/firstcommit"); // We expect firstcommit to appear by id Assert.AreEqual("42e4e7c5e507e113ebbb7801b16b52cf867b7ce1", advertisedRef.ObjectId.Name); // ..and by name as the bundle created a new ref Assert.AreEqual("42e4e7c5e507e113ebbb7801b16b52cf867b7ce1", newRepo.Resolve(("refs/heads/firstcommit")).Name); } #endregion /** * Incremental bundle test * * @throws Exception */ #region testWrite1 [Test] public void testWrite1() { byte[] bundle; // Create a small bundle, an early commit bundle = makeBundle("refs/heads/aa", db.Resolve("a").Name, null); // Then we clone a new repo from that bundle and do a simple test. This // makes sure // we could read the bundle we created. Repository newRepo = createNewEmptyRepo(); FetchResult fetchResult = fetchFromBundle(newRepo, bundle); Ref advertisedRef = fetchResult.GetAdvertisedRef("refs/heads/aa"); Assert.AreEqual(db.Resolve("a").Name, advertisedRef.ObjectId.Name); Assert.AreEqual(db.Resolve("a").Name, newRepo.Resolve("refs/heads/aa").Name); Assert.IsNull(newRepo.Resolve("refs/heads/a")); // Next an incremental bundle bundle = makeBundle( "refs/heads/cc", db.Resolve("c").Name, new GitSharp.RevWalk.RevWalk(db).parseCommit(db.Resolve("a").ToObjectId())); fetchResult = fetchFromBundle(newRepo, bundle); advertisedRef = fetchResult.GetAdvertisedRef("refs/heads/cc"); Assert.AreEqual(db.Resolve("c").Name, advertisedRef.ObjectId.Name); Assert.AreEqual(db.Resolve("c").Name, newRepo.Resolve("refs/heads/cc").Name); Assert.IsNull(newRepo.Resolve("refs/heads/c")); Assert.IsNull(newRepo.Resolve("refs/heads/a")); // still unknown try { // Check that we actually needed the first bundle Repository newRepo2 = createNewEmptyRepo(); fetchResult = fetchFromBundle(newRepo2, bundle); Assert.Fail("We should not be able to fetch from bundle with prerequisites that are not fulfilled"); } catch (MissingBundlePrerequisiteException e) { Assert.IsTrue(e.Message.IndexOf(db.Resolve("refs/heads/a").Name) >= 0); } } #endregion #endregion #region Other methods #region fetchFromBundle private FetchResult fetchFromBundle(Repository newRepo, byte[] bundle) { var uri = new URIish("in-memory://"); var @in = new MemoryStream(bundle); var rs = new RefSpec("refs/heads/*:refs/heads/*"); var refs = new HashSet<RefSpec>(Enumerable.Repeat(rs, 1)); return new TransportBundleStream(newRepo, uri, @in).fetch(NullProgressMonitor.Instance, refs); } #endregion #region makeBundle private byte[] makeBundle(String name, String anObjectToInclude, RevCommit assume) { BundleWriter bw = new BundleWriter(db, NullProgressMonitor.Instance); bw.include(name, ObjectId.FromString(anObjectToInclude)); if (assume != null) { bw.assume(assume); } var @out = new MemoryStream(); bw.writeBundle(@out); return @out.ToArray(); } #endregion #endregion >>>>>>> #region Test methods #region testWrite0 [Test] public void testWrite0() { // Create a tiny bundle, (well one of) the first commits only byte[] bundle = makeBundle("refs/heads/firstcommit", "42e4e7c5e507e113ebbb7801b16b52cf867b7ce1", null); // Then we clone a new repo from that bundle and do a simple test. This // makes sure // we could read the bundle we created. Repository newRepo = createNewEmptyRepo(); FetchResult fetchResult = fetchFromBundle(newRepo, bundle); Ref advertisedRef = fetchResult.GetAdvertisedRef("refs/heads/firstcommit"); // We expect firstcommit to appear by id Assert.AreEqual("42e4e7c5e507e113ebbb7801b16b52cf867b7ce1", advertisedRef.ObjectId.Name); // ..and by name as the bundle created a new ref Assert.AreEqual("42e4e7c5e507e113ebbb7801b16b52cf867b7ce1", newRepo.Resolve(("refs/heads/firstcommit")).Name); } #endregion /** * Incremental bundle test * * @throws Exception */ #region testWrite1 [Test] public void testWrite1() { byte[] bundle; // Create a small bundle, an early commit bundle = makeBundle("refs/heads/aa", db.Resolve("a").Name, null); // Then we clone a new repo from that bundle and do a simple test. This // makes sure // we could read the bundle we created. Repository newRepo = createNewEmptyRepo(); FetchResult fetchResult = fetchFromBundle(newRepo, bundle); Ref advertisedRef = fetchResult.GetAdvertisedRef("refs/heads/aa"); Assert.AreEqual(db.Resolve("a").Name, advertisedRef.ObjectId.Name); Assert.AreEqual(db.Resolve("a").Name, newRepo.Resolve("refs/heads/aa").Name); Assert.IsNull(newRepo.Resolve("refs/heads/a")); // Next an incremental bundle bundle = makeBundle( "refs/heads/cc", db.Resolve("c").Name, new GitSharp.RevWalk.RevWalk(db).parseCommit(db.Resolve("a").ToObjectId())); fetchResult = fetchFromBundle(newRepo, bundle); advertisedRef = fetchResult.GetAdvertisedRef("refs/heads/cc"); Assert.AreEqual(db.Resolve("c").Name, advertisedRef.ObjectId.Name); Assert.AreEqual(db.Resolve("c").Name, newRepo.Resolve("refs/heads/cc").Name); Assert.IsNull(newRepo.Resolve("refs/heads/c")); Assert.IsNull(newRepo.Resolve("refs/heads/a")); // still unknown try { // Check that we actually needed the first bundle Repository newRepo2 = createNewEmptyRepo(); fetchResult = fetchFromBundle(newRepo2, bundle); Assert.Fail("We should not be able to fetch from bundle with prerequisites that are not fulfilled"); } catch (MissingBundlePrerequisiteException e) { Assert.IsTrue(e.Message.IndexOf(db.Resolve("refs/heads/a").Name) >= 0); } } #endregion #endregion #region Other methods #region fetchFromBundle private FetchResult fetchFromBundle(Repository newRepo, byte[] bundle) { var uri = new URIish("in-memory://"); var @in = new MemoryStream(bundle); var rs = new RefSpec("refs/heads/*:refs/heads/*"); var refs = new List<RefSpec>{rs}; return new TransportBundleStream(newRepo, uri, @in).fetch(NullProgressMonitor.Instance, refs); } #endregion #region makeBundle private byte[] makeBundle(String name, String anObjectToInclude, RevCommit assume) { BundleWriter bw = new BundleWriter(db, NullProgressMonitor.Instance); bw.include(name, ObjectId.FromString(anObjectToInclude)); if (assume != null) { bw.assume(assume); } var @out = new MemoryStream(); bw.writeBundle(@out); return @out.ToArray(); } #endregion #endregion
<<<<<<< /// <summary> /// Invoked whenever application code or internal processes (such as a rebuilding /// layout pass) call ApplyTemplate. In simplest terms, this means the method is /// called just before a UI element displays in your app. Override this method to /// influence the default post-template logic of a class. /// </summary> protected async override void OnApplyTemplate() ======= /// <inheritdoc/> protected override void OnApplyTemplate() >>>>>>> /// <inheritdoc/> protected async override void OnApplyTemplate()
<<<<<<< /// <summary> /// Pack file signature that occurs at file header - identifies file as Git /// packfile formatted. /// <para /> /// <b>This constant is fixed and is defined by the Git packfile format.</b> /// </summary> public static readonly byte[] PACK_SIGNATURE = { (byte)'P', (byte)'A', (byte)'C', (byte)'K' }; /// <summary> /// Native character encoding for commit messages, file names... /// </summary> public const string CHARACTER_ENCODING = "UTF-8"; /// <summary> /// Native character encoding for commit messages, file names... /// </summary> public static readonly Encoding CHARSET = Encoding.GetEncoding(CHARACTER_ENCODING); ======= /** * Pack file signature that occurs at file header - identifies file as Git * packfile formatted. * <p> * <b>This constant is fixed and is defined by the Git packfile format.</b> */ public static byte[] PACK_SIGNATURE = { (byte)'P', (byte)'A', (byte)'C', (byte)'K' }; public static EncoderFallback ENCODINGFALLBACK = new EncoderExceptionFallback(); public static DecoderFallback DECODINGFALLBACK = new DecoderExceptionFallback(); /** Native character encoding for commit messages, file names... */ public static string CHARACTER_ENCODING = "UTF-8"; /** Native character encoding for commit messages, file names... */ public static Encoding CHARSET = Encoding.GetEncoding(CHARACTER_ENCODING,ENCODINGFALLBACK,DECODINGFALLBACK); /** Default main branch name */ public static string MASTER = "master"; >>>>>>> /// <summary> /// Pack file signature that occurs at file header - identifies file as Git /// packfile formatted. /// <para /> /// <b>This constant is fixed and is defined by the Git packfile format.</b> /// </summary> public static readonly byte[] PACK_SIGNATURE = { (byte)'P', (byte)'A', (byte)'C', (byte)'K' }; public static EncoderFallback ENCODINGFALLBACK = new EncoderExceptionFallback(); public static DecoderFallback DECODINGFALLBACK = new DecoderExceptionFallback(); /// <summary> /// Native character encoding for commit messages, file names... /// </summary> public const string CHARACTER_ENCODING = "UTF-8"; public static Encoding CHARSET = Encoding.GetEncoding(CHARACTER_ENCODING,ENCODINGFALLBACK,DECODINGFALLBACK);
<<<<<<< data.Add("sessionid", steamWeb.SessionId); ======= data.Add("sessionid", SessionId); data.Add("serverid", "1"); >>>>>>> data.Add("sessionid", steamWeb.SessionId); data.Add("serverid", "1"); <<<<<<< data.Add("sessionid", steamWeb.SessionId); ======= data.Add("sessionid", SessionId); data.Add("serverid", "1"); >>>>>>> data.Add("sessionid", steamWeb.SessionId); data.Add("serverid", "1"); <<<<<<< data.Add("sessionid", steamWeb.SessionId); data.Add("tradeofferid", tradeOfferId); ======= data.Add("sessionid", SessionId); data.Add("serverid", "1"); >>>>>>> data.Add("sessionid", steamWeb.SessionId); data.Add("tradeofferid", tradeOfferId); data.Add("serverid", "1"); <<<<<<< data.Add("sessionid", steamWeb.SessionId); ======= data.Add("sessionid", SessionId); data.Add("serverid", "1"); >>>>>>> data.Add("sessionid", steamWeb.SessionId); data.Add("serverid", "1"); <<<<<<< data.Add("sessionid", steamWeb.SessionId); ======= data.Add("sessionid", SessionId); data.Add("serverid", "1"); >>>>>>> data.Add("sessionid", steamWeb.SessionId); data.Add("serverid", "1"); <<<<<<< data.Add("sessionid", steamWeb.SessionId); ======= data.Add("sessionid", SessionId); data.Add("serverid", "1"); >>>>>>> data.Add("sessionid", steamWeb.SessionId); data.Add("serverid", "1");
<<<<<<< protected string _botName; public LogLevel OutputLevel; public LogLevel FileLogLevel; ======= protected string _Bot; public LogLevel OutputToConsole; public LogLevel OutputToLogfile; >>>>>>> protected string _botName; public LogLevel OutputLevel; public LogLevel FileLogLevel; <<<<<<< public Log(string logFile, string botName = "", LogLevel consoleLogLevel = LogLevel.Info, LogLevel fileLogLevel = LogLevel.Debug) ======= public Log (string logFile, string botName = "", LogLevel outputConsole = LogLevel.Info, LogLevel outputFile = LogLevel.Info) >>>>>>> public Log(string logFile, string botName = "", LogLevel consoleLogLevel = LogLevel.Info, LogLevel fileLogLevel = LogLevel.Info) <<<<<<< _botName = botName; OutputLevel = consoleLogLevel; FileLogLevel = fileLogLevel; ======= _Bot = botName; OutputToLogfile = outputFile; OutputToConsole = outputConsole; >>>>>>> _botName = botName; OutputLevel = consoleLogLevel; FileLogLevel = fileLogLevel; <<<<<<< if(level >= FileLogLevel) { _FileStream.WriteLine(formattedString); } if(level >= OutputLevel) { _OutputLineToConsole(level, formattedString); } } private string GetLogBotName() { if(_botName == null) { return "(System) "; } else if(ShowBotName) { return _botName + " "; } return ""; ======= if( level >= OutputToLogfile ) _FileStream.WriteLine (formattedString); if( level >= OutputToConsole ) _OutputLineToConsole (level, formattedString); >>>>>>> if(level >= FileLogLevel) { _FileStream.WriteLine(formattedString); } if(level >= OutputLevel) { _OutputLineToConsole(level, formattedString); } } private string GetLogBotName() { if(_botName == null) { return "(System) "; } else if(ShowBotName) { return _botName + " "; } return "";
<<<<<<< public HttpWebResponse Request(string url, string method, NameValueCollection data = null, bool ajax = true) ======= public static HttpWebResponse Request (string url, string method, NameValueCollection data = null, CookieContainer cookies = null, bool ajax = true, string referer = "") >>>>>>> public HttpWebResponse Request(string url, string method, NameValueCollection data = null, bool ajax = true, string referer = "")
<<<<<<< new Bot(info, config.ApiKey, (Bot bot, SteamID sid) => { return new SimpleUserHandler(bot, sid); }, true); ======= try { new Bot(info, config.ApiKey); } catch (Exception e) { mainLog.Error("Error With Bot: " + e); crashes++; } >>>>>>> try { new Bot(info, config.ApiKey, (Bot bot, SteamID sid) => { return new SimpleUserHandler(bot, sid); }, true); } catch (Exception e) { mainLog.Error("Error With Bot: " + e); crashes++; }
<<<<<<< Admins = config.Admins; this.apiKey = apiKey; ======= SchemaLang = config.SchemaLang != null && config.SchemaLang.Length == 2 ? config.SchemaLang.ToLower() : "en"; Admins = config.Admins; this.ApiKey = !String.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey; >>>>>>> SchemaLang = config.SchemaLang != null && config.SchemaLang.Length == 2 ? config.SchemaLang.ToLower() : "en"; Admins = config.Admins; this.ApiKey = !String.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey; <<<<<<< GetUserHandler (CurrentTrade.OtherSID).OnTradeTimeout(); ======= GetUserHandler (CurrentTrade.OtherSID).OnTradeTimeout(); } /// <summary> /// Create a new trade offer with the specified partner /// </summary> /// <param name="other">SteamId of the partner</param> /// <returns></returns> public TradeOffer NewTradeOffer(SteamID other) { return tradeOfferManager.NewOffer(other); } /// <summary> /// Try to get a specific trade offer using the offerid /// </summary> /// <param name="offerId"></param> /// <param name="tradeOffer"></param> /// <returns></returns> public bool TryGetTradeOffer(string offerId, out TradeOffer tradeOffer) { return tradeOfferManager.GetOffer(offerId, out tradeOffer); >>>>>>> GetUserHandler (CurrentTrade.OtherSID).OnTradeTimeout(); } /// <summary> /// Create a new trade offer with the specified partner /// </summary> /// <param name="other">SteamId of the partner</param> /// <returns></returns> public TradeOffer NewTradeOffer(SteamID other) { return tradeOfferManager.NewOffer(other); } /// <summary> /// Try to get a specific trade offer using the offerid /// </summary> /// <param name="offerId"></param> /// <param name="tradeOffer"></param> /// <returns></returns> public bool TryGetTradeOffer(string offerId, out TradeOffer tradeOffer) { return tradeOfferManager.GetOffer(offerId, out tradeOffer); <<<<<<< log.Info ("Bot sent other: {0}", response); ======= log.Info ("Bot sent other: " + response); >>>>>>> log.Info ("Bot sent other: {0}", response); <<<<<<< void HandleSteamMessage (CallbackMsg msg) ======= void HandleSteamMessage(ICallbackMsg msg) >>>>>>> void HandleSteamMessage(ICallbackMsg msg) <<<<<<< log.Debug ("Connection Callback: {0}", callback.Result); ======= log.Debug ("Connection Callback: " + callback.Result); >>>>>>> log.Debug ("Connection Callback: {0}", callback.Result); <<<<<<< log.Debug("Logged On Callback: {0}", callback.Result); ======= log.Debug ("Logged On Callback: " + callback.Result); >>>>>>> log.Debug("Logged On Callback: {0}", callback.Result); <<<<<<< log.Error("Login Error: {0}", callback.Result); ======= log.Error ("Login Error: " + callback.Result); >>>>>>> log.Error("Login Error: {0}", callback.Result); <<<<<<< log.Info ("Downloading Schema..."); Trade.CurrentSchema = Schema.FetchSchema (apiKey); log.Success ("Schema Downloaded!"); ======= log.Info ("Downloading Schema..."); Trade.CurrentSchema = Schema.FetchSchema (ApiKey, SchemaLang); log.Success ("Schema Downloaded!"); >>>>>>> log.Info ("Downloading Schema..."); Trade.CurrentSchema = Schema.FetchSchema (ApiKey, SchemaLang); log.Success ("Schema Downloaded!"); <<<<<<< log.Success ("Steam Bot Logged In Completely!"); ======= log.Success ("Steam Bot Logged In Completely!"); IsLoggedIn = true; >>>>>>> log.Success ("Steam Bot Logged In Completely!"); <<<<<<< log.Info ("Chat Message from {0}: {1}", SteamFriends.GetFriendPersonaName (callback.Sender), ======= log.Info (String.Format ("Chat Message from {0}: {1}", SteamFriends.GetFriendPersonaName (callback.Sender), >>>>>>> log.Info ("Chat Message from {0}: {1}", SteamFriends.GetFriendPersonaName (callback.Sender), <<<<<<< ); GetUserHandler(callback.Sender).OnMessage(callback.Message, type); ======= )); GetUserHandler(callback.Sender).OnMessageHandler(callback.Message, type); >>>>>>> ); GetUserHandler(callback.Sender).OnMessageHandler(callback.Message, type); <<<<<<< log.Debug("Trade Status: {0}", callback.Response); log.Info ("Trade Accepted!"); ======= log.Debug ("Trade Status: " + callback.Response); log.Info ("Trade Accepted!"); >>>>>>> log.Debug("Trade Status: {0}", callback.Response); log.Info ("Trade Accepted!"); <<<<<<< log.Warn("Trade failed: {0}", callback.Response); CloseTrade (); ======= log.Warn ("Trade failed: " + callback.Response); CloseTrade (); >>>>>>> log.Warn("Trade failed: {0}", callback.Response); CloseTrade (); <<<<<<< log.Warn("Logged off Steam. Reason: {0}", callback.Result); ======= log.Warn ("Logged Off: " + callback.Result); >>>>>>> log.Warn("Logged off Steam. Reason: {0}", callback.Result); <<<<<<< if(IsLoggedIn) { IsLoggedIn = false; CloseTrade(); log.Warn("Disconnected from Steam Network!"); } SteamClient.Connect (); ======= IsLoggedIn = false; CloseTrade (); log.Warn ("Disconnected from Steam Network!"); SteamClient.Connect (); }); #endregion #region Notifications msg.Handle<SteamBot.SteamNotifications.NotificationCallback>(callback => { //currently only appears to be of trade offer if (callback.Notifications.Count != 0) { foreach (var notification in callback.Notifications) { log.Info(notification.UserNotificationType + " notification"); } } // Get offers only if cookies are valid if (CheckCookies()) tradeOfferManager.GetOffers(); }); msg.Handle<SteamBot.SteamNotifications.CommentNotificationCallback>(callback => { //various types of comment notifications on profile/activity feed etc //log.Info("received CommentNotificationCallback"); //log.Info("New Commments " + callback.CommentNotifications.CountNewComments); //log.Info("New Commments Owners " + callback.CommentNotifications.CountNewCommentsOwner); //log.Info("New Commments Subscriptions" + callback.CommentNotifications.CountNewCommentsSubscriptions); >>>>>>> if(IsLoggedIn) { IsLoggedIn = false; CloseTrade(); log.Warn("Disconnected from Steam Network!"); } SteamClient.Connect (); }); #endregion #region Notifications msg.Handle<SteamBot.SteamNotifications.NotificationCallback>(callback => { //currently only appears to be of trade offer if (callback.Notifications.Count != 0) { foreach (var notification in callback.Notifications) { log.Info(notification.UserNotificationType + " notification"); } } // Get offers only if cookies are valid if (CheckCookies()) tradeOfferManager.GetOffers(); }); msg.Handle<SteamBot.SteamNotifications.CommentNotificationCallback>(callback => { //various types of comment notifications on profile/activity feed etc //log.Info("received CommentNotificationCallback"); //log.Info("New Commments " + callback.CommentNotifications.CountNewComments); //log.Info("New Commments Owners " + callback.CommentNotifications.CountNewCommentsOwner); //log.Info("New Commments Subscriptions" + callback.CommentNotifications.CountNewCommentsSubscriptions); <<<<<<< void OnUpdateMachineAuthCallback (SteamUser.UpdateMachineAuthCallback machineAuth, JobID jobId) ======= void OnUpdateMachineAuthCallback(SteamUser.UpdateMachineAuthCallback machineAuth) >>>>>>> void OnUpdateMachineAuthCallback(SteamUser.UpdateMachineAuthCallback machineAuth) <<<<<<< JobID = jobId, // so we respond to the correct server job ======= JobID = machineAuth.JobID, // so we respond to the correct server job >>>>>>> JobID = machineAuth.JobID, // so we respond to the correct server job
<<<<<<< public const String HideSystemTray = nameof(HideSystemTray); ======= public const String ShowReadme = nameof(ShowReadme); >>>>>>> public const String HideSystemTray = nameof(HideSystemTray); public const String ShowReadme = nameof(ShowReadme);
<<<<<<< private async void syncWithGoogle(SyncCommand syncCommand) ======= private void syncWithGoogle(SyncCommand syncCommand, bool autoSync) >>>>>>> private async void syncWithGoogle(SyncCommand syncCommand, bool autoSync) <<<<<<< // Get Access Token / Authorization UserCredential myCredential = await GetAuthorization(); // Create a new Google Drive API Service DriveService service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = myCredential, ApplicationName = Defs.ProductName }); ======= // abort when user cancelled or didn't provide config if (!GetConfiguration()) throw new PlgxException(Defs.ProductName() + " aborted!"); >>>>>>> // abort when user cancelled or didn't provide config if (!GetConfiguration()) throw new PlgxException(Defs.ProductName() + " aborted!"); // Get Access Token / Authorization UserCredential myCredential = await GetAuthorization(); // Create a new Google Drive API Service DriveService service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = myCredential, ApplicationName = Defs.ProductName() }); <<<<<<< var progress = await downloader.DownloadAsync(file.DownloadUrl, fileStream); if (progress.Status == DownloadStatus.Completed) return downloadFilePath; else return string.Empty; ======= ShowMessage("File download failed: " + response.StatusDescription); return null; >>>>>>> var progress = await downloader.DownloadAsync(file.DownloadUrl, fileStream); if (progress.Status == DownloadStatus.Completed) return downloadFilePath; else return null; <<<<<<< // Let the User authorize the access if (myCredential == null || String.IsNullOrEmpty(myCredential.Token.AccessToken)) ======= Uri authUri = arg.RequestUserAuthorization(state); GoogleAuthenticateForm form1; if (m_entry != null) form1 = new GoogleAuthenticateForm(authUri, m_entry.Strings.Get(PwDefs.UserNameField).ReadString(), m_entry.Strings.Get(PwDefs.PasswordField)); else form1 = new GoogleAuthenticateForm(authUri, string.Empty, null); UIUtil.ShowDialogAndDestroy(form1); if (!form1.Success) throw new PlgxException("Authorization failed: " + form1.Code); try { state = arg.ProcessUserAuthorization(form1.Code, state); } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { // fetch http status code and msg HttpStatusCode status = 0; String statusDesc = string.Empty; if (ex.InnerException is WebException && ((WebException)ex.InnerException).Response is HttpWebResponse) { status = ((HttpWebResponse)((WebException)ex.InnerException).Response).StatusCode; statusDesc = ((HttpWebResponse)((WebException)ex.InnerException).Response).StatusDescription; } if (status == HttpStatusCode.Unauthorized) { // authorization above was successful - so client secret must be invalid throw new PlgxException("Authorization failed: Invalid OAuth 2.0 Client Secret"); } else if (status != 0) { throw new PlgxException("Authorization failed: HTTP staus " + status + " " + statusDesc); } else { throw ex; // sth. else went wrong } } // save the refresh token if new or different if (!String.IsNullOrEmpty(state.RefreshToken) && (m_refreshToken == null || state.RefreshToken != m_refreshToken.ReadString())) >>>>>>> // Let the User authorize the access if (myCredential == null || String.IsNullOrEmpty(myCredential.Token.AccessToken))
<<<<<<< private System.Tuple<List<LogEventInfo>, List<AsyncContinuation>> _reusableLogEvents; private bool _missingServiceTypes; ======= private Tuple<List<LogEventInfo>, List<AsyncContinuation>> _reusableLogEvents; private AsyncHelpersTask? _flushEventsInQueueDelegate; >>>>>>> private Tuple<List<LogEventInfo>, List<AsyncContinuation>> _reusableLogEvents; private AsyncHelpersTask? _flushEventsInQueueDelegate; private bool _missingServiceTypes; <<<<<<< #if NET4_0 newTask.ContinueWith(completedTask => TaskCompletion(completedTask, reusableLogEvents)); ======= #if (SILVERLIGHT && !WINDOWS_PHONE) || NET4_0 newTask.ContinueWith(completedTask => TaskCompletion(completedTask, reusableLogEvents), TaskScheduler); >>>>>>> #if NET4_0 newTask.ContinueWith(completedTask => TaskCompletion(completedTask, reusableLogEvents), TaskScheduler);
<<<<<<< private void ParseTargetElement(Target target, ValidatedConfigurationElement targetElement, Dictionary<string, ValidatedConfigurationElement> typeNameToDefaultTargetParameters = null) ======= private Target CreateTargetType(string targetTypeName) { Target newTarget = null; try { newTarget = _configurationItemFactory.Targets.CreateInstance(targetTypeName); if (newTarget == null) throw new NLogConfigurationException($"Factory returned null for target type: {targetTypeName}"); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; var configException = new NLogConfigurationException($"Failed to create target type: {targetTypeName}", ex); if (MustThrowConfigException(configException)) throw configException; } return newTarget; } void ParseDefaultTargetParameters(ILoggingConfigurationElement defaultTargetElement, string targetType, Dictionary<string, ILoggingConfigurationElement> typeNameToDefaultTargetParameters) { typeNameToDefaultTargetParameters[targetType.Trim()] = defaultTargetElement; } private void ParseTargetElement(Target target, ILoggingConfigurationElement targetElement, Dictionary<string, ILoggingConfigurationElement> typeNameToDefaultTargetParameters = null) >>>>>>> private Target CreateTargetType(string targetTypeName) { Target newTarget = null; try { newTarget = _configurationItemFactory.Targets.CreateInstance(targetTypeName); if (newTarget == null) throw new NLogConfigurationException($"Factory returned null for target type: {targetTypeName}"); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; var configException = new NLogConfigurationException($"Failed to create target type: {targetTypeName}", ex); if (MustThrowConfigException(configException)) throw configException; } return newTarget; } private void ParseTargetElement(Target target, ValidatedConfigurationElement targetElement, Dictionary<string, ValidatedConfigurationElement> typeNameToDefaultTargetParameters = null) <<<<<<< private void SetPropertyFromElement(object o, ValidatedConfigurationElement element) ======= private void SetPropertyFromElement(object o, ILoggingConfigurationElement childElement, ILoggingConfigurationElement parentElement) >>>>>>> private void SetPropertyFromElement(object o, ValidatedConfigurationElement childElement, ILoggingConfigurationElement parentElement) <<<<<<< string wrapperTypeName = GetConfigItemTypeAttribute(defaultWrapperElement, "targets"); Target wrapperTargetInstance = _configurationItemFactory.Targets.CreateInstance(wrapperTypeName); ======= string wrapperTypeName = GetConfigItemTypeAttribute(defaultParameters, "targets"); Target wrapperTargetInstance = CreateTargetType(wrapperTypeName); >>>>>>> string wrapperTypeName = GetConfigItemTypeAttribute(defaultWrapperElement, "targets"); Target wrapperTargetInstance = CreateTargetType(wrapperTypeName);
<<<<<<< Initialize(); } } private void Initialize() { try { ======= PropertyHelper.CheckRequiredParameters(this); >>>>>>> Initialize(); } } private void Initialize() { try { PropertyHelper.CheckRequiredParameters(this);
<<<<<<< countdownEvent.Wait(8000); ======= countdownEvent.Wait(20000); //we need some extra time for completion Thread.Sleep(1000); >>>>>>> countdownEvent.Wait(8000); //we need some extra time for completion Thread.Sleep(1000);
<<<<<<< using NLog.LayoutRenderers; ======= using System.Linq; >>>>>>> <<<<<<< ======= private readonly Dictionary<string, string> variables = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); >>>>>>> private readonly Dictionary<string, string> variables = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
<<<<<<< var todo = ((Position > text.Length) ? Text.Substring(Position + 1) : ""); return $"done: '{done}'. current: '{current}'. todo: '{todo}'"; ======= var todo = ((Position > _text.Length) ? Text.Substring(Position + 1) : ""); return string.Format("done: '{0}'. current: '{1}'. todo: '{2}'", done, current, todo); >>>>>>> var todo = ((Position > _text.Length) ? Text.Substring(Position + 1) : ""); return $"done: '{done}'. current: '{current}'. todo: '{todo}'";
<<<<<<< using System; using System.IO; using System.Runtime.CompilerServices; using NLog.Internal; ======= >>>>>>> <<<<<<< string name = !StringHelpers.IsNullOrWhiteSpace(callerFilePath) ? Path.GetFileNameWithoutExtension(callerFilePath) : null; var logger = StringHelpers.IsNullOrWhiteSpace(name) ? _logger : LogManager.GetLogger(name); ======= var logger = GetLogger(callerFilePath); >>>>>>> var logger = GetLogger(callerFilePath);
<<<<<<< if (File.Exists(tempFile)) File.Delete(tempFile); ======= LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void RepeatingFooterTest() { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempPath, "file.txt"); try { const string footer = "Footerline"; string archiveFolder = Path.Combine(tempPath, "archive"); var ft = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(archiveFolder, "{####}.txt"), ArchiveAboveSize = 51, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Sequence, Layout = "${message}", Footer = footer, MaxArchiveFiles = 2, }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); for (var i = 0; i < 16; ++i) { logger.Debug("123456789"); } LogManager.Configuration = null; string expectedEnding = footer + ft.LineEnding.NewLineCharacters; AssertFileContentsEndsWith(logFile, expectedEnding, Encoding.UTF8); AssertFileContentsEndsWith(Path.Combine(archiveFolder, "0002.txt"), expectedEnding, Encoding.UTF8); AssertFileContentsEndsWith(Path.Combine(archiveFolder, "0001.txt"), expectedEnding, Encoding.UTF8); Assert.True(!File.Exists(Path.Combine(archiveFolder, "0000.txt"))); } finally { LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); >>>>>>> if (File.Exists(logFile)) File.Delete(logFile); if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void RepeatingFooterTest() { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempPath, "file.txt"); try { const string footer = "Footerline"; string archiveFolder = Path.Combine(tempPath, "archive"); var ft = new FileTarget { FileName = logFile, ArchiveFileName = Path.Combine(archiveFolder, "{####}.txt"), ArchiveAboveSize = 51, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Sequence, Layout = "${message}", Footer = footer, MaxArchiveFiles = 2, }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); for (var i = 0; i < 16; ++i) { logger.Debug("123456789"); } LogManager.Configuration = null; string expectedEnding = footer + ft.LineEnding.NewLineCharacters; AssertFileContentsEndsWith(logFile, expectedEnding, Encoding.UTF8); AssertFileContentsEndsWith(Path.Combine(archiveFolder, "0002.txt"), expectedEnding, Encoding.UTF8); AssertFileContentsEndsWith(Path.Combine(archiveFolder, "0001.txt"), expectedEnding, Encoding.UTF8); Assert.True(!File.Exists(Path.Combine(archiveFolder, "0000.txt"))); } finally { LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile);
<<<<<<< using (var scope = new InternalLoggerScope()) { CreateConfigurationFromString(@" <nlog internalLogFile='c:\file.txt' internalLogLevel='Trace' internalLogToConsole='true' internalLogToConsoleError='true' globalThreshold='Warn' throwExceptions='true' internalLogToDiagnostics='true'> </nlog>"); Assert.Same(LogLevel.Trace, InternalLogger.LogLevel); Assert.True(InternalLogger.LogToConsole); Assert.True(InternalLogger.LogToConsoleError); Assert.Same(LogLevel.Warn, LogManager.GlobalThreshold); Assert.True(LogManager.ThrowExceptions); Assert.True(InternalLogger.LogToDiagnostics); } ======= InternalLoggingConfigTest(LogLevel.Trace, true, true, LogLevel.Warn, true, true, @"c:\temp\nlog\file.txt"); >>>>>>> InternalLoggingConfigTest(LogLevel.Trace, true, true, LogLevel.Warn, true, true, @"c:\temp\nlog\file.txt"); <<<<<<< InternalLogger.LogToDiagnostics = true; ======= LogManager.ThrowConfigExceptions = null; >>>>>>> LogManager.ThrowConfigExceptions = null; InternalLogger.LogToDiagnostics = true; <<<<<<< Assert.True(InternalLogger.LogToDiagnostics); ======= Assert.Null(LogManager.ThrowConfigExceptions); } } private void InternalLoggingConfigTest(LogLevel logLevel, bool logToConsole, bool logToConsoleError, LogLevel globalThreshold, bool throwExceptions, bool? throwConfigExceptions, string file) { var logLevelString = logLevel.ToString(); var internalLogToConsoleString = logToConsole.ToString().ToLower(); var internalLogToConsoleErrorString = logToConsoleError.ToString().ToLower(); var globalThresholdString = globalThreshold.ToString(); var throwExceptionsString = throwExceptions.ToString().ToLower(); var throwConfigExceptionsString = throwConfigExceptions == null ? "" : throwConfigExceptions.ToString().ToLower(); using (new InternalLoggerScope()) { CreateConfigurationFromString(string.Format(@" <nlog internalLogFile='{0}' internalLogLevel='{1}' internalLogToConsole='{2}' internalLogToConsoleError='{3}' globalThreshold='{4}' throwExceptions='{5}' throwConfigExceptions='{6}'> </nlog>", file, logLevelString, internalLogToConsoleString, internalLogToConsoleErrorString, globalThresholdString, throwExceptionsString, throwConfigExceptionsString)); Assert.Same(logLevel, InternalLogger.LogLevel); Assert.Equal(file, InternalLogger.LogFile); Assert.Equal(logToConsole, InternalLogger.LogToConsole); Assert.Equal(logToConsoleError, InternalLogger.LogToConsoleError); Assert.Same(globalThreshold, LogManager.GlobalThreshold); Assert.Equal(throwExceptions, LogManager.ThrowExceptions); Assert.Equal(throwConfigExceptions, LogManager.ThrowConfigExceptions); >>>>>>> Assert.Null(LogManager.ThrowConfigExceptions); Assert.True(InternalLogger.LogToDiagnostics); } } private void InternalLoggingConfigTest(LogLevel logLevel, bool logToConsole, bool logToConsoleError, LogLevel globalThreshold, bool throwExceptions, bool? throwConfigExceptions, string file) { var logLevelString = logLevel.ToString(); var internalLogToConsoleString = logToConsole.ToString().ToLower(); var internalLogToConsoleErrorString = logToConsoleError.ToString().ToLower(); var globalThresholdString = globalThreshold.ToString(); var throwExceptionsString = throwExceptions.ToString().ToLower(); var throwConfigExceptionsString = throwConfigExceptions == null ? "" : throwConfigExceptions.ToString().ToLower(); using (new InternalLoggerScope()) { CreateConfigurationFromString(string.Format(@" <nlog internalLogFile='{0}' internalLogLevel='{1}' internalLogToConsole='{2}' internalLogToConsoleError='{3}' globalThreshold='{4}' throwExceptions='{5}' throwConfigExceptions='{6}'> </nlog>", file, logLevelString, internalLogToConsoleString, internalLogToConsoleErrorString, globalThresholdString, throwExceptionsString, throwConfigExceptionsString)); Assert.Same(logLevel, InternalLogger.LogLevel); Assert.Equal(file, InternalLogger.LogFile); Assert.Equal(logToConsole, InternalLogger.LogToConsole); Assert.Equal(logToConsoleError, InternalLogger.LogToConsoleError); Assert.Same(globalThreshold, LogManager.GlobalThreshold); Assert.Equal(throwExceptions, LogManager.ThrowExceptions); Assert.Equal(throwConfigExceptions, LogManager.ThrowConfigExceptions);
<<<<<<< #if NETCOREAPP3_1 || NET5_0 [MethodImpl(MethodImplOptions.AggressiveOptimization)] #endif ======= >>>>>>> <<<<<<< #if NETCOREAPP3_1 || NET5_0 [MethodImpl(MethodImplOptions.AggressiveOptimization)] #endif ======= >>>>>>>
<<<<<<< /// Gets the logger with the name of the current class. ======= /// Gets or sets the default culture to use. /// </summary> /// <remarks>This property was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("Use Configuration.DefaultCultureInfo property instead. Marked obsolete before v4.3.11")] public static GetCultureInfo DefaultCultureInfo { get { return () => factory.DefaultCultureInfo ?? CultureInfo.CurrentCulture; } set => throw new NotSupportedException("Setting the DefaultCultureInfo delegate is no longer supported. Use the Configuration.DefaultCultureInfo property to change the default CultureInfo."); } /// <summary> /// Gets the logger with the full name of the current class, so namespace and class name. >>>>>>> /// Gets the logger with the full name of the current class, so namespace and class name.
<<<<<<< if (File.Exists(tempFile)) File.Delete(tempFile); ======= LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); >>>>>>> if (File.Exists(logFile)) File.Delete(logFile); <<<<<<< if (File.Exists(tempFile)) File.Delete(tempFile); ======= LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); >>>>>>> if (File.Exists(logFile)) File.Delete(logFile); <<<<<<< if (File.Exists(tempFile)) File.Delete(tempFile); ======= LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); >>>>>>> if (File.Exists(logFile)) File.Delete(logFile); <<<<<<< if (File.Exists(tempFile)) File.Delete(tempFile); ======= LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); >>>>>>> if (File.Exists(logFile)) File.Delete(logFile); <<<<<<< if (File.Exists(tempFile)) File.Delete(tempFile); ======= LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); >>>>>>> if (File.Exists(logFile)) File.Delete(logFile); <<<<<<< if (File.Exists(tempFile)) File.Delete(tempFile); ======= LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); >>>>>>> if (File.Exists(logFile)) File.Delete(logFile); <<<<<<< if (File.Exists(tempFile)) File.Delete(tempFile); ======= LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); >>>>>>> if (File.Exists(logFile)) File.Delete(logFile); <<<<<<< if (File.Exists(tempFile)) File.Delete(tempFile); ======= LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); >>>>>>> if (File.Exists(logFile)) File.Delete(logFile); <<<<<<< if (File.Exists(tempFile)) File.Delete(tempFile); ======= LogManager.Configuration = null; if (File.Exists(logfile)) File.Delete(logfile); >>>>>>> if (File.Exists(logfile)) File.Delete(logfile); <<<<<<< if (File.Exists(tempFile)) File.Delete(tempFile); ======= LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); >>>>>>> if (File.Exists(logFile)) File.Delete(logFile); <<<<<<< if (File.Exists(tempFile)) File.Delete(tempFile); ======= LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); >>>>>>> if (File.Exists(logFile)) File.Delete(logFile); <<<<<<< if (File.Exists(tempFile)) File.Delete(tempFile); ======= LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); >>>>>>> if (File.Exists(logFile)) File.Delete(logFile); <<<<<<< if (File.Exists(tempFile)) File.Delete(tempFile); ======= LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); >>>>>>> if (File.Exists(logFile)) File.Delete(logFile); <<<<<<< if (File.Exists(tempFile)) File.Delete(tempFile); ======= LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); >>>>>>> if (File.Exists(logFile)) File.Delete(logFile); <<<<<<< if (File.Exists(tempFile)) File.Delete(tempFile); ======= LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); >>>>>>> if (File.Exists(logFile)) File.Delete(logFile); <<<<<<< if (File.Exists(tempFile)) File.Delete(tempFile); ======= LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); >>>>>>> if (File.Exists(logFile)) File.Delete(logFile); <<<<<<< if (File.Exists(tempFile)) File.Delete(tempFile); ======= LogManager.Configuration = null; if (File.Exists(logFile)) File.Delete(logFile); >>>>>>> if (File.Exists(logFile)) File.Delete(logFile); <<<<<<< if (File.Exists(tempFile)) File.Delete(tempFile); ======= LogManager.Configuration = null; if (File.Exists(logfile)) File.Delete(logfile); >>>>>>> if (File.Exists(logfile)) File.Delete(logfile);
<<<<<<< var logFile = Path.GetTempFileName(); ======= get { bool[] boolValues = new[] { false, true }; return from useHeader in boolValues from useFooter in boolValues select new object[] { useHeader, useFooter }; } } [Theory] [PropertyData("ReplaceFileContentsOnEachWriteTest_TestParameters")] public void ReplaceFileContentsOnEachWriteTest(bool useHeader, bool useFooter) { const string header = "Headerline", footer = "Footerline"; var tempFile = Path.GetTempFileName(); >>>>>>> get { bool[] boolValues = new[] { false, true }; return from useHeader in boolValues from useFooter in boolValues select new object[] { useHeader, useFooter }; } } [Theory] [PropertyData("ReplaceFileContentsOnEachWriteTest_TestParameters")] public void ReplaceFileContentsOnEachWriteTest(bool useHeader, bool useFooter) { const string header = "Headerline", footer = "Footerline"; var tempFile = Path.GetTempFileName(); <<<<<<< }); ======= }; if (useHeader) fileTarget.Header = header; if (useFooter) fileTarget.Footer = footer; >>>>>>> }); if (useHeader) fileTarget.Header = header; if (useFooter) fileTarget.Footer = footer; <<<<<<< AssertFileContents(logFile, "Warn ccc\n", Encoding.UTF8); ======= >>>>>>>
<<<<<<< [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] ======= public void IncludeGdcNoEmptyJsonProperties() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <targets> <target name='asyncDebug' type='AsyncWrapper' timeToSleepBetweenBatches='0'> <target name='debug' type='Debug' > <layout type=""JsonLayout"" IncludeGdc='true' ExcludeProperties='Excluded1,Excluded2' ExcludeEmptyProperties='true'> </layout> </target> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='asyncDebug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); var logEventInfo = CreateLogEventWithExcluded(); logEventInfo.Properties.Add("EmptyProp", ""); logEventInfo.Properties.Add("EmptyProp1", null); logEventInfo.Properties.Add("EmptyProp2", new DummyContextLogger() { Value = null }); logEventInfo.Properties.Add("EmptyProp3", new DummyContextLogger() { Value = "" }); logEventInfo.Properties.Add("NoEmptyProp4", new DummyContextLogger() { Value = "hello" }); GlobalDiagnosticsContext.Clear(); foreach (var prop in logEventInfo.Properties) if (prop.Key.ToString() != "Excluded1" && prop.Key.ToString() != "Excluded2") GlobalDiagnosticsContext.Set(prop.Key.ToString(), prop.Value); logEventInfo.Properties.Clear(); logger.Debug(logEventInfo); LogManager.Flush(); AssertDebugLastMessage("debug", ExpectedExcludeEmptyPropertiesWithExcludes); } [Fact] >>>>>>> public void IncludeGdcNoEmptyJsonProperties() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <targets> <target name='asyncDebug' type='AsyncWrapper' timeToSleepBetweenBatches='0'> <target name='debug' type='Debug' > <layout type=""JsonLayout"" IncludeGdc='true' ExcludeProperties='Excluded1,Excluded2' ExcludeEmptyProperties='true'> </layout> </target> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='asyncDebug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); var logEventInfo = CreateLogEventWithExcluded(); logEventInfo.Properties.Add("EmptyProp", ""); logEventInfo.Properties.Add("EmptyProp1", null); logEventInfo.Properties.Add("EmptyProp2", new DummyContextLogger() { Value = null }); logEventInfo.Properties.Add("EmptyProp3", new DummyContextLogger() { Value = "" }); logEventInfo.Properties.Add("NoEmptyProp4", new DummyContextLogger() { Value = "hello" }); GlobalDiagnosticsContext.Clear(); foreach (var prop in logEventInfo.Properties) if (prop.Key.ToString() != "Excluded1" && prop.Key.ToString() != "Excluded2") GlobalDiagnosticsContext.Set(prop.Key.ToString(), prop.Value); logEventInfo.Properties.Clear(); logger.Debug(logEventInfo); LogManager.Flush(); AssertDebugLastMessage("debug", ExpectedExcludeEmptyPropertiesWithExcludes); } [Fact] [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] <<<<<<< [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] ======= public void IncludeMdlcNoEmptyJsonProperties() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <targets> <target name='asyncDebug' type='AsyncWrapper' timeToSleepBetweenBatches='0'> <target name='debug' type='Debug' > <layout type=""JsonLayout"" IncludeMdlc='true' ExcludeProperties='Excluded1,Excluded2' ExcludeEmptyProperties='true'> </layout> </target> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='asyncDebug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); var logEventInfo = CreateLogEventWithExcluded(); logEventInfo.Properties.Add("EmptyProp", ""); logEventInfo.Properties.Add("EmptyProp1", null); logEventInfo.Properties.Add("EmptyProp2", new DummyContextLogger() { Value = null }); logEventInfo.Properties.Add("EmptyProp3", new DummyContextLogger() { Value = "" }); logEventInfo.Properties.Add("NoEmptyProp4", new DummyContextLogger() { Value = "hello" }); MappedDiagnosticsLogicalContext.Clear(); foreach (var prop in logEventInfo.Properties) if (prop.Key.ToString() != "Excluded1" && prop.Key.ToString() != "Excluded2") MappedDiagnosticsLogicalContext.Set(prop.Key.ToString(), prop.Value); logEventInfo.Properties.Clear(); logger.Debug(logEventInfo); LogManager.Flush(); AssertDebugLastMessage("debug", ExpectedExcludeEmptyPropertiesWithExcludes); } [Fact] >>>>>>> [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public void IncludeMdlcNoEmptyJsonProperties() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog throwExceptions='true'> <targets> <target name='asyncDebug' type='AsyncWrapper' timeToSleepBetweenBatches='0'> <target name='debug' type='Debug' > <layout type=""JsonLayout"" IncludeMdlc='true' ExcludeProperties='Excluded1,Excluded2' ExcludeEmptyProperties='true'> </layout> </target> </target> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='asyncDebug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); var logEventInfo = CreateLogEventWithExcluded(); logEventInfo.Properties.Add("EmptyProp", ""); logEventInfo.Properties.Add("EmptyProp1", null); logEventInfo.Properties.Add("EmptyProp2", new DummyContextLogger() { Value = null }); logEventInfo.Properties.Add("EmptyProp3", new DummyContextLogger() { Value = "" }); logEventInfo.Properties.Add("NoEmptyProp4", new DummyContextLogger() { Value = "hello" }); MappedDiagnosticsLogicalContext.Clear(); foreach (var prop in logEventInfo.Properties) if (prop.Key.ToString() != "Excluded1" && prop.Key.ToString() != "Excluded2") MappedDiagnosticsLogicalContext.Set(prop.Key.ToString(), prop.Value); logEventInfo.Properties.Clear(); logger.Debug(logEventInfo); LogManager.Flush(); AssertDebugLastMessage("debug", ExpectedExcludeEmptyPropertiesWithExcludes); } [Fact] [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")]
<<<<<<< /// <summary> /// Resolve from DI <see cref="LogFactory.ServiceRepository"/> /// </summary> /// <remarks>Avoid calling this while handling a LogEvent, since random deadlocks can occur.</remarks> protected T ResolveService<T>() where T : class { return LoggingConfiguration.GetServiceResolver().ResolveService<T>(); } ======= /// <summary> /// Should the exception be rethrown? /// </summary> /// <param name="exception"></param> /// <remarks>Upgrade to private protected when using C# 7.2 </remarks> internal bool ExceptionMustBeRethrown(Exception exception) { return exception.MustBeRethrown(this); } >>>>>>> /// <summary> /// Resolve from DI <see cref="LogFactory.ServiceRepository"/> /// </summary> /// <remarks>Avoid calling this while handling a LogEvent, since random deadlocks can occur.</remarks> protected T ResolveService<T>() where T : class { return LoggingConfiguration.GetServiceResolver().ResolveService<T>(); } /// <summary> /// Should the exception be rethrown? /// </summary> /// <param name="exception"></param> /// <remarks>Upgrade to private protected when using C# 7.2 </remarks> internal bool ExceptionMustBeRethrown(Exception exception) { return exception.MustBeRethrown(this); }
<<<<<<< #region Compositio unit test [Fact] public void When_WrappedInCompsition_Ignore_Wrapper_Methods_In_Callstack() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.When_WrappedInCompsition_Ignore_Wrapper_Methods_In_Callstack"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); var logger = LogManager.GetLogger("A"); logger.Warn("direct"); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); CompositeWrapper wrappedLogger = new CompositeWrapper(); wrappedLogger.Log("wrapped"); AssertDebugLastMessage("debug", string.Format("{0}|wrapped", currentMethodFullName)); } public class CompositeWrapper { private readonly MyWrapper wrappedLogger; public CompositeWrapper() { wrappedLogger = new MyWrapper(); } public void Log(string what) { wrappedLogger.Log(typeof(CompositeWrapper), what); } } public abstract class BaseWrapper { public void Log(string what) { InternalLog(typeof(BaseWrapper), what); } public void Log(Type type, string what) //overloaded with type for composition { InternalLog(type, what); } protected abstract void InternalLog(Type type, string what); } public class MyWrapper : BaseWrapper { private readonly ILogger wrapperLogger; public MyWrapper() { wrapperLogger = LogManager.GetLogger("WrappedLogger"); } protected override void InternalLog(Type type, string what) //added type for composition { LogEventInfo info = new LogEventInfo(LogLevel.Warn, wrapperLogger.Name, what); // Provide BaseWrapper as wrapper type. // Expected: UserStackFrame should point to the method that calls a // method of BaseWrapper. wrapperLogger.Log(type, info); } } #endregion ======= private class MyLogger : Logger { } [Fact] public void CallsiteBySubclass_interface() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)); Assert.True(logger is MyLogger, "logger isn't MyLogger"); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_interface msg"); } [Fact] public void CallsiteBySubclass_mylogger() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); MyLogger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)) as MyLogger; Assert.NotNull(logger); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_mylogger msg"); } [Fact] public void CallsiteBySubclass_logger() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)) as Logger; Assert.NotNull(logger); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_logger msg"); } >>>>>>> #region Compositio unit test [Fact] public void When_WrappedInCompsition_Ignore_Wrapper_Methods_In_Callstack() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.When_WrappedInCompsition_Ignore_Wrapper_Methods_In_Callstack"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); var logger = LogManager.GetLogger("A"); logger.Warn("direct"); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); CompositeWrapper wrappedLogger = new CompositeWrapper(); wrappedLogger.Log("wrapped"); AssertDebugLastMessage("debug", string.Format("{0}|wrapped", currentMethodFullName)); } public class CompositeWrapper { private readonly MyWrapper wrappedLogger; public CompositeWrapper() { wrappedLogger = new MyWrapper(); } public void Log(string what) { wrappedLogger.Log(typeof(CompositeWrapper), what); } } public abstract class BaseWrapper { public void Log(string what) { InternalLog(typeof(BaseWrapper), what); } public void Log(Type type, string what) //overloaded with type for composition { InternalLog(type, what); } protected abstract void InternalLog(Type type, string what); } public class MyWrapper : BaseWrapper { private readonly ILogger wrapperLogger; public MyWrapper() { wrapperLogger = LogManager.GetLogger("WrappedLogger"); } protected override void InternalLog(Type type, string what) //added type for composition { LogEventInfo info = new LogEventInfo(LogLevel.Warn, wrapperLogger.Name, what); // Provide BaseWrapper as wrapper type. // Expected: UserStackFrame should point to the method that calls a // method of BaseWrapper. wrapperLogger.Log(type, info); } } #endregion private class MyLogger : Logger { } [Fact] public void CallsiteBySubclass_interface() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)); Assert.True(logger is MyLogger, "logger isn't MyLogger"); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_interface msg"); } [Fact] public void CallsiteBySubclass_mylogger() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); MyLogger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)) as MyLogger; Assert.NotNull(logger); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_mylogger msg"); } [Fact] public void CallsiteBySubclass_logger() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)) as Logger; Assert.NotNull(logger); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_logger msg"); }
<<<<<<< /// <summary> /// Gets or sets the log4j:event logger-xml-attribute (Default ${logger}) /// </summary> /// <docgen category='Payload Options' order='10' /> public Layout LoggerName { get => Renderer.LoggerName; set => Renderer.LoggerName = value; } /// <summary> /// Gets or sets the AppInfo field. By default it's the friendly name of the current AppDomain. /// </summary> /// <docgen category='Payload Options' order='10' /> public Layout AppInfo { get => Renderer.AppInfo; set => Renderer.AppInfo = value; } /// <summary> /// Gets or sets whether the log4j:throwable xml-element should be written as CDATA /// </summary> /// <docgen category='Payload Options' order='10' /> public bool WriteThrowableCData { get => Renderer.WriteThrowableCData; set => Renderer.WriteThrowableCData = value; } ======= /// <summary> /// Gets or sets a value indicating whether to include call site (class and method name) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeCallSite { get => Renderer.IncludeCallSite; set => Renderer.IncludeCallSite = value; } /// <summary> /// Gets or sets a value indicating whether to include source info (file name and line number) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeSourceInfo { get => Renderer.IncludeSourceInfo; set => Renderer.IncludeSourceInfo = value; } >>>>>>> /// <summary> /// Gets or sets the log4j:event logger-xml-attribute (Default ${logger}) /// </summary> /// <docgen category='Payload Options' order='10' /> public Layout LoggerName { get => Renderer.LoggerName; set => Renderer.LoggerName = value; } /// <summary> /// Gets or sets the AppInfo field. By default it's the friendly name of the current AppDomain. /// </summary> /// <docgen category='Payload Options' order='10' /> public Layout AppInfo { get => Renderer.AppInfo; set => Renderer.AppInfo = value; } /// <summary> /// Gets or sets whether the log4j:throwable xml-element should be written as CDATA /// </summary> /// <docgen category='Payload Options' order='10' /> public bool WriteThrowableCData { get => Renderer.WriteThrowableCData; set => Renderer.WriteThrowableCData = value; } /// <summary> /// Gets or sets a value indicating whether to include call site (class and method name) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeCallSite { get => Renderer.IncludeCallSite; set => Renderer.IncludeCallSite = value; } /// <summary> /// Gets or sets a value indicating whether to include source info (file name and line number) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeSourceInfo { get => Renderer.IncludeSourceInfo; set => Renderer.IncludeSourceInfo = value; }
<<<<<<< /* private static MethodInfo _GetMouthCellAtCellM = AccessTools.Method(typeof(OxygenBreather), "GetMouthCellAtCell"); private delegate int GetMouthCellAtCell_Delegate(int cell, CellOffset[] offsets); private static GetMouthCellAtCell_Delegate _GetMouthCellAtCell = (GetMouthCellAtCell_Delegate)Delegate.CreateDelegate(typeof(GetMouthCellAtCell_Delegate), _GetMouthCellAtCellM); */ ======= >>>>>>> /* private static MethodInfo _GetMouthCellAtCellM = AccessTools.Method(typeof(OxygenBreather), "GetMouthCellAtCell"); private delegate int GetMouthCellAtCell_Delegate(int cell, CellOffset[] offsets); private static GetMouthCellAtCell_Delegate _GetMouthCellAtCell = (GetMouthCellAtCell_Delegate)Delegate.CreateDelegate(typeof(GetMouthCellAtCell_Delegate), _GetMouthCellAtCellM); */
<<<<<<< string buildingName = building.name.Replace("Complete", string.Empty); bool colorAsOffset = ColorHelper.GetComponentMaterialColor(building, out Color color); ======= string buildingName = building.name.Replace("Complete", string.Empty); try { if (!State.TypeFilter.Check(buildingName)) { return; } } catch (Exception e) { State.Logger.Log("Error while filtering buildings"); State.Logger.Log(e); } SimHashes material = MaterialHelper.ExtractMaterial(building); Color32 color; if (State.ConfiguratorState.Enabled) { switch (State.ConfiguratorState.ColorMode) { case ColorMode.Json: color = material.GetMaterialColorForType(buildingName); break; case ColorMode.DebugColor: color = material.ToDebugColor(); break; default: color = ColorHelper.DefaultColor; break; } } else { color = ColorHelper.DefaultColor; } >>>>>>> string buildingName = building.name.Replace("Complete", string.Empty); bool colorAsOffset = ColorHelper.GetComponentMaterialColor(building, out Color color); try { if (!State.TypeFilter.Check(buildingName)) { return; } } catch (Exception e) { State.Logger.Log("Error while filtering buildings"); State.Logger.Log(e); } SimHashes material = MaterialHelper.ExtractMaterial(building); <<<<<<< bool toggleMaterialColor = Traverse.Create(toggle_info).Field<SimViewMode>("simView").Value == (SimViewMode)IDs.ToggleMaterialColorOverlayID; ======= //bool toggleMaterialColor = ((OverlayMenu.OverlayToggleInfo)toggle_info).simView bool toggleMaterialColor = (HashedString)GetField(toggle_info, "simView") == IDs.MaterialColorOverlayHS; >>>>>>> bool toggleMaterialColor = Traverse.Create(toggle_info).Field<HashedString>("simView").Value == IDs.ToggleMaterialColorOverlayHS;
<<<<<<< using Microsoft.Toolkit.Uwp.Helpers; ======= using Microsoft.Toolkit.Uwp.SampleApp.Controls; >>>>>>> using Microsoft.Toolkit.Uwp.Helpers; using Microsoft.Toolkit.Uwp.SampleApp.Controls; <<<<<<< using Windows.UI.Composition; ======= using Windows.System.Threading; >>>>>>> using Windows.UI.Composition; using Windows.System.Threading; <<<<<<< private Button _searchButton; private bool _hamburgerMenuClosing = false; private Compositor _compositor; private float _defaultShowAnimationDuration = 300; private float _defaultHideAnimationDiration = 150; ======= private XamlRenderService _xamlRenderer = new XamlRenderService(); private ThreadPoolTimer _autocompileTimer; >>>>>>> private Button _searchButton; private bool _hamburgerMenuClosing = false; private Compositor _compositor; private float _defaultShowAnimationDuration = 300; private float _defaultHideAnimationDiration = 150; private XamlRenderService _xamlRenderer = new XamlRenderService(); private ThreadPoolTimer _autocompileTimer; <<<<<<< XamlCodeRenderer.XamlSource = this._currentSample.UpdatedXamlCode; ======= XamlCodeRenderer.Text = _currentSample.UpdatedXamlCode; >>>>>>> XamlCodeRenderer.Text = _currentSample.UpdatedXamlCode;
<<<<<<< using DotVVM.Framework.Binding.Properties; ======= using DotVVM.Framework.Binding; using System.Linq; >>>>>>> using DotVVM.Framework.Binding.Properties; using DotVVM.Framework.Binding; using System.Linq;
<<<<<<< private DoubleAnimation _leftCommandAnimation; private Storyboard _leftCommandStoryboard; private DoubleAnimation _rightCommandAnimation; private Storyboard _rightCommandStoryboard; ======= private bool _justFinishedSwiping; >>>>>>> private DoubleAnimation _leftCommandAnimation; private Storyboard _leftCommandStoryboard; private DoubleAnimation _rightCommandAnimation; private Storyboard _rightCommandStoryboard; private bool _justFinishedSwiping;
<<<<<<< #if NET5_0 return ref MemoryMarshal.GetArrayDataReference(array); #elif NETCORE_RUNTIME var arrayData = Unsafe.As<RawArrayData>(array); ======= #if NETCORE_RUNTIME var arrayData = Unsafe.As<RawArrayData>(array)!; >>>>>>> #if NET5_0 return ref MemoryMarshal.GetArrayDataReference(array); #elif NETCORE_RUNTIME var arrayData = Unsafe.As<RawArrayData>(array)!; <<<<<<< #if NET5_0 ref T r0 = ref MemoryMarshal.GetArrayDataReference(array); ref T ri = ref Unsafe.Add(ref r0, (nint)(uint)i); return ref ri; #elif NETCORE_RUNTIME var arrayData = Unsafe.As<RawArrayData>(array); ======= #if NETCORE_RUNTIME var arrayData = Unsafe.As<RawArrayData>(array)!; >>>>>>> #if NET5_0 ref T r0 = ref MemoryMarshal.GetArrayDataReference(array); ref T ri = ref Unsafe.Add(ref r0, (nint)(uint)i); return ref ri; #elif NETCORE_RUNTIME var arrayData = Unsafe.As<RawArrayData>(array)!;
<<<<<<< OneDriveStorageFolder currentFolder = null; SampleController.Current.DisplayWaitRing = true; ======= Services.OneDrive.OneDriveStorageFolder currentFolder = null; Shell.Current.DisplayWaitRing = true; >>>>>>> Services.OneDrive.OneDriveStorageFolder currentFolder = null; SampleController.Current.DisplayWaitRing = true; <<<<<<< await OneDriveSampleHelpers.RenameAsync((OneDriveStorageItem)((AppBarButton)e.OriginalSource).DataContext); OneDriveItemsList.ItemsSource = _currentFolder.GetItemsAsync(); ======= if (_indexProvider == 3) { await OneDriveSampleHelpers.RenameAsync((Toolkit.Services.OneDrive.OneDriveStorageItem)((AppBarButton)e.OriginalSource).DataContext); OneDriveItemsList.ItemsSource = await _graphCurrentFolder.GetItemsAsync(20); } else { await OneDriveSampleHelpers.RenameAsync((Services.OneDrive.OneDriveStorageItem)((AppBarButton)e.OriginalSource).DataContext); OneDriveItemsList.ItemsSource = _currentFolder.GetItemsAsync(); } >>>>>>> if (_indexProvider == 3) { await OneDriveSampleHelpers.RenameAsync((Toolkit.Services.OneDrive.OneDriveStorageItem)((AppBarButton)e.OriginalSource).DataContext); OneDriveItemsList.ItemsSource = await _graphCurrentFolder.GetItemsAsync(20); } else { await OneDriveSampleHelpers.RenameAsync((Services.OneDrive.OneDriveStorageItem)((AppBarButton)e.OriginalSource).DataContext); OneDriveItemsList.ItemsSource = _currentFolder.GetItemsAsync(); } <<<<<<< SampleController.Current.DisplayWaitRing = true; var file = (OneDriveStorageItem)((AppBarButton)e.OriginalSource).DataContext; using (var stream = await file.GetThumbnailAsync(ThumbnailSize.Large)) ======= Shell.Current.DisplayWaitRing = true; if (_indexProvider == 3) >>>>>>> SampleController.Current.DisplayWaitRing = true; if (_indexProvider == 3)
<<<<<<< config.Markup.AddMarkupControl("sample", "EmbeddedResourceControls_Button", "embedded://EmbeddedResourceControls/Button.dotcontrol"); ======= config.Markup.AddMarkupControl("sample", "ControlWithButton", "Views/ControlSamples/Repeater/SampleControl/ControlWithButton.dotcontrol"); >>>>>>> config.Markup.AddMarkupControl("sample", "ControlWithButton", "Views/ControlSamples/Repeater/SampleControl/ControlWithButton.dotcontrol"); config.Markup.AddMarkupControl("sample", "EmbeddedResourceControls_Button", "embedded://EmbeddedResourceControls/Button.dotcontrol");
<<<<<<< [Optional] Vector4 vertexColor; [Optional] float FaceSign; ======= [Optional] Vector4 VertexColor; >>>>>>> [Optional] Vector4 VertexColor; [Optional] float FaceSign; <<<<<<< new Dependency("SurfaceDescriptionInputs.vertexColor", "FragInputs.color"), new Dependency("SurfaceDescriptionInputs.FaceSign", "FragInputs.isFrontFace"), ======= new Dependency("SurfaceDescriptionInputs.VertexColor", "FragInputs.color"), >>>>>>> new Dependency("SurfaceDescriptionInputs.VertexColor", "FragInputs.color"), new Dependency("SurfaceDescriptionInputs.FaceSign", "FragInputs.isFrontFace"),
<<<<<<< this.vmMapper = vmMapper; this.staticCommandBindingCompiler = staticCommandBindingCompiler; ======= this.javascriptTranslator = javascriptTranslator; >>>>>>> this.staticCommandBindingCompiler = staticCommandBindingCompiler; this.javascriptTranslator = javascriptTranslator; <<<<<<< return new StaticCommandJavascriptProperty(FormatJavascript(this.staticCommandBindingCompiler.CompileToJavascript(dataContext, expression.Expression), niceMode: configuration.Debug)); ======= return new StaticCommandJavascriptProperty(FormatJavascript(new StaticCommandBindingCompiler(javascriptTranslator).CompileToJavascript(dataContext, expression.Expression), niceMode: configuration.Debug)); >>>>>>> return new StaticCommandJavascriptProperty(FormatJavascript(this.staticCommandBindingCompiler.CompileToJavascript(dataContext, expression.Expression), niceMode: configuration.Debug));
<<<<<<< using System; using System.Collections.Generic; ======= #nullable enable >>>>>>> #nullable enable using System; using System.Collections.Generic; <<<<<<< [Obsolete("The DefaultRouteName property is not supported - the classic SPA more (URLs with #/) was removed from DotVVM. See https://www.dotvvm.com/docs/tutorials/basics-single-page-applications-spa/latest for more details.")] public string DefaultRouteName ======= public string? DefaultRouteName >>>>>>> [Obsolete("The DefaultRouteName property is not supported - the classic SPA more (URLs with #/) was removed from DotVVM. See https://www.dotvvm.com/docs/tutorials/basics-single-page-applications-spa/latest for more details.")] public string? DefaultRouteName <<<<<<< = DotvvmProperty.Register<string, SpaContentPlaceHolder>(p => p.DefaultRouteName); #pragma warning restore 618 ======= = DotvvmProperty.Register<string?, SpaContentPlaceHolder>(p => p.DefaultRouteName); >>>>>>> = DotvvmProperty.Register<string, SpaContentPlaceHolder>(p => p.DefaultRouteName); #pragma warning restore 618 <<<<<<< [Obsolete("The PrefixRouteName property is not supported - the classic SPA more (URLs with #/) was removed from DotVVM. See https://www.dotvvm.com/docs/tutorials/basics-single-page-applications-spa/latest for more details.")] public string PrefixRouteName ======= public string? PrefixRouteName >>>>>>> [Obsolete("The PrefixRouteName property is not supported - the classic SPA more (URLs with #/) was removed from DotVVM. See https://www.dotvvm.com/docs/tutorials/basics-single-page-applications-spa/latest for more details.")] public string? PrefixRouteName <<<<<<< = DotvvmProperty.Register<string, SpaContentPlaceHolder>(c => c.PrefixRouteName, null); #pragma warning restore 618 ======= = DotvvmProperty.Register<string?, SpaContentPlaceHolder>(c => c.PrefixRouteName, null); >>>>>>> = DotvvmProperty.Register<string, SpaContentPlaceHolder>(c => c.PrefixRouteName, null); #pragma warning restore 618 <<<<<<< context.ResourceManager.RegisterProcessor(new ResourceManagement.SpaModeResourceProcessor(context.Configuration)); ======= base.OnInit(context); } private string? GetCorrectSpaUrlPrefix(IDotvvmRequestContext context) { var routePath = ""; if (!string.IsNullOrEmpty(PrefixRouteName)) { routePath = context.Configuration.RouteTable[PrefixRouteName].Url.Trim('/'); } else { return null; } >>>>>>> context.ResourceManager.RegisterProcessor(new ResourceManagement.SpaModeResourceProcessor(context.Configuration));
<<<<<<< if (GetType() == typeof(Literal)) LifecycleRequirements = ControlLifecycleRequirements.None; ======= RenderSpanElement = false; >>>>>>> RenderSpanElement = false; if (GetType() == typeof(Literal)) LifecycleRequirements = ControlLifecycleRequirements.None; <<<<<<< protected override void AddAttributesToRender(IHtmlWriter writer, IDotvvmRequestContext context) ======= public bool IsFormattingRequired => !string.IsNullOrEmpty(FormatString) || ValueType != FormatValueType.Text || NeedsFormatting(GetValueBinding(TextProperty)); protected internal override void OnPreRender(Hosting.IDotvvmRequestContext context) >>>>>>> public bool IsFormattingRequired => !string.IsNullOrEmpty(FormatString) || ValueType != FormatValueType.Text || NeedsFormatting(GetValueBinding(TextProperty)); protected internal override void OnPreRender(Hosting.IDotvvmRequestContext context)
<<<<<<< lastStopwatchState = AddTraceData(lastStopwatchState, RequestTracingConstants.CommandExecuted, context, Stopwatch); ======= >>>>>>>
<<<<<<< Parent.GetClosestWithPropertyValue(out numberOfDataContextChanges, control => (bool)control.GetValue(Internal.IsControlBindingTargetProperty)); ======= GetClosestWithPropertyValue(out numberOfDataContextChanges, (control, _) => (bool)control.GetValue(Internal.IsControlBindingTargetProperty)); >>>>>>> Parent.GetClosestWithPropertyValue(out numberOfDataContextChanges, (control, _) => (bool)control.GetValue(Internal.IsControlBindingTargetProperty));
<<<<<<< [Fact] public void Error_InvalidLocationFallback() { RunInAllBrowsers(browser => { browser.NavigateToUrl(SamplesRouteUrls.Errors_InvalidLocationFallback); AssertUI.TextEquals(browser.First(".exceptionType"), "System.NotSupportedException"); AssertUI.TextEquals(browser.First(".exceptionMessage"), "LocationFallback does not support ILocalResourceLocations."); }); } ======= [Fact] public void Error_InvalidServiceDirective() { RunInAllBrowsers(browser => { browser.NavigateToUrl(SamplesRouteUrls.Errors_InvalidServiceDirective); AssertUI.TextEquals(browser.First("exceptionType", By.ClassName), "DotVVM.Framework.Compilation.DotvvmCompilationException"); AssertUI.TextEquals(browser.First("exceptionMessage", By.ClassName), "DotVVM.InvalidNamespace.NonExistingService is not a valid type."); }); } >>>>>>> [Fact] public void Error_InvalidServiceDirective() { RunInAllBrowsers(browser => { browser.NavigateToUrl(SamplesRouteUrls.Errors_InvalidServiceDirective); AssertUI.TextEquals(browser.First("exceptionType", By.ClassName), "DotVVM.Framework.Compilation.DotvvmCompilationException"); AssertUI.TextEquals(browser.First("exceptionMessage", By.ClassName), "DotVVM.InvalidNamespace.NonExistingService is not a valid type."); }); } [Fact] public void Error_InvalidLocationFallback() { RunInAllBrowsers(browser => { browser.NavigateToUrl(SamplesRouteUrls.Errors_InvalidLocationFallback); AssertUI.TextEquals(browser.First(".exceptionType"), "System.NotSupportedException"); AssertUI.TextEquals(browser.First(".exceptionMessage"), "LocationFallback does not support ILocalResourceLocations."); }); }
<<<<<<< [TestMethod] public void Control_CheckBox_InRepeater() { RunInAllBrowsers(browser => { browser.NavigateToUrl(SamplesRouteUrls.ControlSamples_CheckBox_InRepeater); var repeater = browser.Single("div[data-ui='repeater']"); var checkBoxes = browser.FindElements("label[data-ui='checkBox']"); var checkBox = checkBoxes.ElementAt(0).Single("input"); checkBox.Click(); checkBox.CheckIfIsChecked(); browser.Single("span[data-ui='selectedColors']") .CheckIfInnerText(s => s.Contains("orange")); checkBox = checkBoxes.ElementAt(1).Single("input"); checkBox.Click(); checkBox.CheckIfIsChecked(); browser.Single("span[data-ui='selectedColors']") .CheckIfInnerText(s => s.Contains("orange") && s.Contains("red")); checkBox = checkBoxes.ElementAt(2).Single("input"); checkBox.Click(); checkBox.CheckIfIsChecked(); browser.Single("span[data-ui='selectedColors']") .CheckIfInnerText(s => s.Contains("orange") && s.Contains("red") && s.Contains("black")); checkBoxes = browser.FindElements("label[data-ui='checkBox']"); browser.First("[data-ui='set-server-values']").Click(); checkBoxes.ElementAt(0).Single("input").CheckIfIsChecked(); checkBoxes.ElementAt(2).Single("input").CheckIfIsChecked(); browser.Single("span[data-ui='selectedColors']") .CheckIfInnerText(s => s.Contains("orange") && s.Contains("black")); }); } //[TestMethod] //public void Control_CheckBox_NullCollection() //{ // RunInAllBrowsers(browser => // { // browser.NavigateToUrl(SamplesRouteUrls.ControlSamples_CheckBox_CheckedItemsNull); // }); //} ======= [TestMethod] public void Control_CheckBox_Indeterminate() { RunInAllBrowsers(browser => { browser.NavigateToUrl(SamplesRouteUrls.ControlSamples_CheckBox_Indeterminate); var checkBox = browser.First("input[type=checkbox]"); var reset = browser.First("input[type=button]"); var value = browser.First("span.value"); value.CheckIfTextEquals("Indeterminate"); checkBox.Click(); value.CheckIfTextEquals("Other"); reset.Click(); value.CheckIfTextEquals("Indeterminate"); }); } >>>>>>> [TestMethod] public void Control_CheckBox_InRepeater() { RunInAllBrowsers(browser => { browser.NavigateToUrl(SamplesRouteUrls.ControlSamples_CheckBox_InRepeater); var repeater = browser.Single("div[data-ui='repeater']"); var checkBoxes = browser.FindElements("label[data-ui='checkBox']"); var checkBox = checkBoxes.ElementAt(0).Single("input"); checkBox.Click(); checkBox.CheckIfIsChecked(); browser.Single("span[data-ui='selectedColors']") .CheckIfInnerText(s => s.Contains("orange")); checkBox = checkBoxes.ElementAt(1).Single("input"); checkBox.Click(); checkBox.CheckIfIsChecked(); browser.Single("span[data-ui='selectedColors']") .CheckIfInnerText(s => s.Contains("orange") && s.Contains("red")); checkBox = checkBoxes.ElementAt(2).Single("input"); checkBox.Click(); checkBox.CheckIfIsChecked(); browser.Single("span[data-ui='selectedColors']") .CheckIfInnerText(s => s.Contains("orange") && s.Contains("red") && s.Contains("black")); checkBoxes = browser.FindElements("label[data-ui='checkBox']"); browser.First("[data-ui='set-server-values']").Click(); checkBoxes.ElementAt(0).Single("input").CheckIfIsChecked(); checkBoxes.ElementAt(2).Single("input").CheckIfIsChecked(); browser.Single("span[data-ui='selectedColors']") .CheckIfInnerText(s => s.Contains("orange") && s.Contains("black")); }); } //[TestMethod] //public void Control_CheckBox_NullCollection() //{ // RunInAllBrowsers(browser => // { // browser.NavigateToUrl(SamplesRouteUrls.ControlSamples_CheckBox_CheckedItemsNull); // }); //} [TestMethod] public void Control_CheckBox_Indeterminate() { RunInAllBrowsers(browser => { browser.NavigateToUrl(SamplesRouteUrls.ControlSamples_CheckBox_Indeterminate); var checkBox = browser.First("input[type=checkbox]"); var reset = browser.First("input[type=button]"); var value = browser.First("span.value"); value.CheckIfTextEquals("Indeterminate"); checkBox.Click(); value.CheckIfTextEquals("Other"); reset.Click(); value.CheckIfTextEquals("Indeterminate"); }); }
<<<<<<< using Microsoft.Extensions.DependencyInjection; ======= using DotVVM.Framework.Runtime.Tracing; >>>>>>> using Microsoft.Extensions.DependencyInjection; using DotVVM.Framework.Runtime.Tracing; <<<<<<< private long AddTraceData(long lastStopwatchState, string eventName, IDotvvmRequestContext context, IStopwatch stopwatch) { long nextStopwatchState = stopwatch.GetElapsedMiliseconds(); context.TraceData.Add(eventName, nextStopwatchState - lastStopwatchState); return nextStopwatchState; } private object ExecuteStaticCommandPlan(StaticCommandInvocationPlan plan, Queue<JToken> arguments, IDotvvmRequestContext context) { var methodArgs = plan.Arguments.Select((a, index) => a.Type == StaticCommandParameterType.Argument ? arguments.Dequeue().ToObject((Type)a.Arg) : a.Type == StaticCommandParameterType.Constant || a.Type == StaticCommandParameterType.DefaultValue ? a.Arg : a.Type == StaticCommandParameterType.Inject ? context.Services.GetRequiredService((Type)a.Arg) : a.Type == StaticCommandParameterType.Invocation ? ExecuteStaticCommandPlan((StaticCommandInvocationPlan)a.Arg, arguments, context) : throw new NotSupportedException("" + a.Type) ).ToArray(); return plan.Method.Invoke(plan.Method.IsStatic ? null : methodArgs.First(), plan.Method.IsStatic ? methodArgs : methodArgs.Skip(1).ToArray()); } ======= >>>>>>> private object ExecuteStaticCommandPlan(StaticCommandInvocationPlan plan, Queue<JToken> arguments, IDotvvmRequestContext context) { var methodArgs = plan.Arguments.Select((a, index) => a.Type == StaticCommandParameterType.Argument ? arguments.Dequeue().ToObject((Type)a.Arg) : a.Type == StaticCommandParameterType.Constant || a.Type == StaticCommandParameterType.DefaultValue ? a.Arg : a.Type == StaticCommandParameterType.Inject ? context.Services.GetRequiredService((Type)a.Arg) : a.Type == StaticCommandParameterType.Invocation ? ExecuteStaticCommandPlan((StaticCommandInvocationPlan)a.Arg, arguments, context) : throw new NotSupportedException("" + a.Type) ).ToArray(); return plan.Method.Invoke(plan.Method.IsStatic ? null : methodArgs.First(), plan.Method.IsStatic ? methodArgs : methodArgs.Skip(1).ToArray()); }
<<<<<<< using Redwood.Framework.Hosting; using Redwood.Framework.Controls; ======= >>>>>>> using Redwood.Framework.Hosting; using Redwood.Framework.Controls; <<<<<<< var redwoodConfiguration = new RedwoodConfiguration() { ApplicationPhysicalPath = applicationPhysicalPath }; redwoodConfiguration.ResourceRepo.Register("knockout-core", new ScriptResource("/Scripts/knockout-3.2.0.js")); redwoodConfiguration.ResourceRepo.Register("knockout", new ScriptResource("/Scripts/knockout.mapping-latest.js", "knockout-core")); redwoodConfiguration.ResourceRepo.Register("redwood", new ScriptResource("/Scripts/Redwood.js", "knockout")); ======= RedwoodConfiguration redwoodConfiguration; app.UseRedwood(applicationPhysicalPath, out redwoodConfiguration); >>>>>>> RedwoodConfiguration redwoodConfiguration; app.UseRedwood(applicationPhysicalPath, out redwoodConfiguration); redwoodConfiguration.ResourceRepo.Register("knockout-core", new ScriptResource("/Scripts/knockout-3.2.0.js")); redwoodConfiguration.ResourceRepo.Register("knockout", new ScriptResource("/Scripts/knockout.mapper.js", "knockout-core")); redwoodConfiguration.ResourceRepo.Register("redwood", new ScriptResource("/Scripts/Redwood.js", "knockout"));
<<<<<<< using DotVVM.Framework.Binding.Expressions; using DotVVM.Framework.Binding.Properties; ======= >>>>>>> using DotVVM.Framework.Binding.Expressions; using DotVVM.Framework.Binding.Properties; <<<<<<< private void DataBind(IDotvvmRequestContext context) ======= private void CallGridViewDataSetRefreshRequest(IRefreshableGridViewDataSet refreshableGridViewDataSet) { refreshableGridViewDataSet.RequestRefresh(); } private void DataBind(Hosting.IDotvvmRequestContext context) >>>>>>> private void CallGridViewDataSetRefreshRequest(IRefreshableGridViewDataSet refreshableGridViewDataSet) { refreshableGridViewDataSet.RequestRefresh(); } private void DataBind(IDotvvmRequestContext context) <<<<<<< placeholder.SetValue(Internal.PathFragmentProperty, GetPathFragmentExpression() + "/[$index]"); placeholder.SetValue(Internal.ClientIDFragmentProperty, GetValueRaw(Internal.CurrentIndexBindingProperty)); writer.WriteKnockoutDataBindComment("if", "ko.unwrap(ko.unwrap($gridViewDataSet).EditRowId) !== ko.unwrap($data[ko.unwrap(ko.unwrap($gridViewDataSet).PrimaryKeyPropertyName)])"); ======= placeholder.SetValue(Internal.PathFragmentProperty, JavascriptCompilationHelper.AddIndexerToViewModel(GetPathFragmentExpression(), "$index")); placeholder.SetValue(Internal.ClientIDFragmentProperty, "$index()"); writer.WriteKnockoutDataBindComment("if", "ko.unwrap(ko.unwrap($gridViewDataSet).RowEditOptions().EditRowId) !== ko.unwrap($data[ko.unwrap(ko.unwrap($gridViewDataSet).RowEditOptions().PrimaryKeyPropertyName)])"); >>>>>>> placeholder.SetValue(Internal.PathFragmentProperty, GetPathFragmentExpression() + "/[$index]"); placeholder.SetValue(Internal.ClientIDFragmentProperty, GetValueRaw(Internal.CurrentIndexBindingProperty)); writer.WriteKnockoutDataBindComment("if", "ko.unwrap(ko.unwrap($gridViewDataSet).RowEditOptions().EditRowId) !== ko.unwrap($data[ko.unwrap(ko.unwrap($gridViewDataSet).RowEditOptions().PrimaryKeyPropertyName)])"); <<<<<<< placeholderEdit.SetValue(Internal.PathFragmentProperty, GetPathFragmentExpression() + "/[$index]"); placeholderEdit.SetValue(Internal.ClientIDFragmentProperty, GetValueRaw(Internal.CurrentIndexBindingProperty)); writer.WriteKnockoutDataBindComment("if", "ko.unwrap(ko.unwrap($gridViewDataSet).EditRowId) === ko.unwrap($data[ko.unwrap(ko.unwrap($gridViewDataSet).PrimaryKeyPropertyName)])"); ======= placeholderEdit.SetValue(Internal.PathFragmentProperty, JavascriptCompilationHelper.AddIndexerToViewModel(GetPathFragmentExpression(), "$index")); placeholderEdit.SetValue(Internal.ClientIDFragmentProperty, "$index()"); writer.WriteKnockoutDataBindComment("if", "ko.unwrap(ko.unwrap($gridViewDataSet).RowEditOptions().EditRowId) === ko.unwrap($data[ko.unwrap(ko.unwrap($gridViewDataSet).RowEditOptions().PrimaryKeyPropertyName)])"); >>>>>>> placeholderEdit.SetValue(Internal.PathFragmentProperty, GetPathFragmentExpression() + "/[$index]"); placeholderEdit.SetValue(Internal.ClientIDFragmentProperty, GetValueRaw(Internal.CurrentIndexBindingProperty)); writer.WriteKnockoutDataBindComment("if", "ko.unwrap(ko.unwrap($gridViewDataSet).RowEditOptions().EditRowId) === ko.unwrap($data[ko.unwrap(ko.unwrap($gridViewDataSet).RowEditOptions().PrimaryKeyPropertyName)])");
<<<<<<< if (await context.IsGrantedAsync(StoresPermissions.Stores.Manage)) { storeManagementMenuItem.AddItem( new ApplicationMenuItem(StoresMenus.StoreOwner, l["Menu:StoreOwner"], "/EShop/Stores/StoreOwners/StoreOwner") ); } ======= if (await context.IsGrantedAsync(StoresPermissions.Transaction.Default)) { var storeAppService = context.ServiceProvider.GetRequiredService<IStoreAppService>(); var defaultStore = (await storeAppService.GetDefaultAsync())?.Id; storeManagementMenuItem.AddItem( new ApplicationMenuItem(StoresMenus.Transaction, l["Menu:Transaction"], "/EShop/Stores/Transactions/Transaction?storeId=" + defaultStore)); } >>>>>>> if (await context.IsGrantedAsync(StoresPermissions.Stores.Manage)) { storeManagementMenuItem.AddItem( new ApplicationMenuItem(StoresMenus.StoreOwner, l["Menu:StoreOwner"], "/EShop/Stores/StoreOwners/StoreOwner") ); } if (await context.IsGrantedAsync(StoresPermissions.Transaction.Default)) { var storeAppService = context.ServiceProvider.GetRequiredService<IStoreAppService>(); var defaultStore = (await storeAppService.GetDefaultAsync())?.Id; storeManagementMenuItem.AddItem( new ApplicationMenuItem(StoresMenus.Transaction, l["Menu:Transaction"], "/EShop/Stores/Transactions/Transaction?storeId=" + defaultStore)); }
<<<<<<< builder.Entity<StoreOwner>(b => { b.ToTable(options.TablePrefix + "StoreOwners", options.Schema); b.ConfigureByConvention(); /* Configure more properties here */ b.HasIndex(x => new {x.OwnerUserId, x.StoreId}) .IsUnique(); }); ======= builder.Entity<Transaction>(b => { b.ToTable(options.TablePrefix + "Transactions", options.Schema); b.ConfigureByConvention(); /* Configure more properties here */ b.Property(x => x.Amount).HasColumnType("decimal(20,8)"); }); >>>>>>> builder.Entity<StoreOwner>(b => { b.ToTable(options.TablePrefix + "StoreOwners", options.Schema); b.ConfigureByConvention(); /* Configure more properties here */ b.HasIndex(x => new {x.OwnerUserId, x.StoreId}) .IsUnique(); }); builder.Entity<Transaction>(b => { b.ToTable(options.TablePrefix + "Transactions", options.Schema); b.ConfigureByConvention(); /* Configure more properties here */ b.Property(x => x.Amount).HasColumnType("decimal(20,8)"); });
<<<<<<< using EasyAbp.EShop.Stores.StoreOwners; ======= using EasyAbp.EShop.Stores.Transactions; >>>>>>> using EasyAbp.EShop.Stores.StoreOwners; using EasyAbp.EShop.Stores.Transactions; <<<<<<< options.AddRepository<StoreOwner, StoreOwnerRepository>(); ======= options.AddRepository<Transaction, TransactionRepository>(); >>>>>>> options.AddRepository<StoreOwner, StoreOwnerRepository>(); options.AddRepository<Transaction, TransactionRepository>();
<<<<<<< using Volo.Abp.ObjectExtending; ======= using EasyAbp.EShop.Stores.Transactions; using EasyAbp.EShop.Stores.Transactions.Dtos; using AutoMapper; >>>>>>> using EasyAbp.EShop.Stores.Transactions; using EasyAbp.EShop.Stores.Transactions.Dtos; using Volo.Abp.ObjectExtending; <<<<<<< CreateMap<Store, StoreDto>() .MapExtraProperties(MappingPropertyDefinitionChecks.Both); CreateMap<CreateUpdateStoreDto, Store>(MemberList.Source) .MapExtraProperties(MappingPropertyDefinitionChecks.Both); CreateMap<StoreOwner, StoreOwnerDto>() .MapExtraProperties(MappingPropertyDefinitionChecks.Both); CreateMap<StoreOwnerDto, StoreOwner>(MemberList.Source) .MapExtraProperties(MappingPropertyDefinitionChecks.Both); ======= CreateMap<Store, StoreDto>(); CreateMap<CreateUpdateStoreDto, Store>(MemberList.Source); CreateMap<Transaction, TransactionDto>(); CreateMap<CreateUpdateTransactionDto, Transaction>(MemberList.Source); >>>>>>> CreateMap<Store, StoreDto>() .MapExtraProperties(MappingPropertyDefinitionChecks.Both); CreateMap<CreateUpdateStoreDto, Store>(MemberList.Source) .MapExtraProperties(MappingPropertyDefinitionChecks.Both); CreateMap<StoreOwner, StoreOwnerDto>() .MapExtraProperties(MappingPropertyDefinitionChecks.Both); CreateMap<StoreOwnerDto, StoreOwner>(MemberList.Source) .MapExtraProperties(MappingPropertyDefinitionChecks.Both); CreateMap<Transaction, TransactionDto>(); CreateMap<CreateUpdateTransactionDto, Transaction>(MemberList.Source);
<<<<<<< DbSet<StoreOwner> StoreOwners { get; set; } ======= DbSet<Transaction> Transactions { get; set; } >>>>>>> DbSet<StoreOwner> StoreOwners { get; set; } DbSet<Transaction> Transactions { get; set; }
<<<<<<< ImmutableArray<CodeAnalysisMetricData> children = await ComputeAsync(GetChildSymbols(@namespace), context).ConfigureAwait(false); ======= var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(semanticModelProvider.Compilation); ImmutableArray<CodeAnalysisMetricData> children = await ComputeAsync(GetChildSymbols(@namespace), semanticModelProvider, cancellationToken).ConfigureAwait(false); >>>>>>> var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(semanticModelProvider.Compilation); ImmutableArray<CodeAnalysisMetricData> children = await ComputeAsync(GetChildSymbols(@namespace), context).ConfigureAwait(false);
<<<<<<< if (isAssertEnabled) { Assert.True(false, string.Format("Expected diagnostic to be on line \"{0}\" was actually on line \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Span, actualLinePosition.Line + 1, FormatDiagnostics(analyzer, diagnostic))); } else { return false; } ======= Assert.True(false, string.Format("Expected diagnostic to be on line \"{0}\" was actually on line \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.StartLinePosition.Line + 1, actualLinePosition.Line + 1, FormatDiagnostics(analyzer, diagnostic))); >>>>>>> if (isAssertEnabled) { Assert.True(false, string.Format("Expected diagnostic to be on line \"{0}\" was actually on line \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.StartLinePosition.Line + 1, actualLinePosition.Line + 1, FormatDiagnostics(analyzer, diagnostic))); } else { return false; } <<<<<<< if (isAssertEnabled) { Assert.True(false, string.Format("Expected diagnostic to start at column \"{0}\" was actually at column \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.StartLinePosition.Character, actualLinePosition.Character + 1, FormatDiagnostics(analyzer, diagnostic))); } else { return false; } ======= Assert.True(false, string.Format("Expected diagnostic to start at column \"{0}\" was actually at column \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.StartLinePosition.Character + 1, actualLinePosition.Character + 1, FormatDiagnostics(analyzer, diagnostic))); >>>>>>> if (isAssertEnabled) { Assert.True(false, string.Format("Expected diagnostic to start at column \"{0}\" was actually at column \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.StartLinePosition.Character + 1, actualLinePosition.Character + 1, FormatDiagnostics(analyzer, diagnostic))); } else { return false; }
<<<<<<< /// Looks up a localized string similar to Uses the unsafe setter of InnerXml property of System.Xml.XmlDocument.. ======= /// Looks up a localized string similar to Providing an insecure XsltSettings instance and an insecure XmlResolver instance to XslCompiledTransform.Load method is potentially unsafe as it allows processing script within XSL, which on an untrusted XSL input may lead to malicious code execution. Either replace the insecure XsltSettings argument with XsltSettings.Default or an instance that has disabled document function and script execution, or replace the XmlResolver argurment with null or an XmlSecureResolver instance. This message may be suppressed [rest of string was truncated]&quot;;. /// </summary> internal static string DoNotUseInsecureXSLTScriptExecutionDescription { get { return ResourceManager.GetString("DoNotUseInsecureXSLTScriptExecutionDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to {0} uses the unsafe setter of InnerXml property of System.Xml.XmlDocument.. >>>>>>> /// Looks up a localized string similar to Providing an insecure XsltSettings instance and an insecure XmlResolver instance to XslCompiledTransform.Load method is potentially unsafe as it allows processing script within XSL, which on an untrusted XSL input may lead to malicious code execution. Either replace the insecure XsltSettings argument with XsltSettings.Default or an instance that has disabled document function and script execution, or replace the XmlResolver argurment with null or an XmlSecureResolver instance. This message may be suppressed [rest of string was truncated]&quot;;. /// </summary> internal static string DoNotUseInsecureXSLTScriptExecutionDescription { get { return ResourceManager.GetString("DoNotUseInsecureXSLTScriptExecutionDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Uses the unsafe setter of InnerXml property of System.Xml.XmlDocument..
<<<<<<< var osPlatformType = osPlatformTypeArray[0]; var platformSpecificOperations = PooledConcurrentDictionary<IOperation, (SmallDictionary<string, PlatformAttributes> attributes, SmallDictionary<string, PlatformAttributes>? csAttributes)>.GetInstance(); ======= var osPlatformTypeArray = osPlatformType != null ? ImmutableArray.Create(osPlatformType) : ImmutableArray<INamedTypeSymbol>.Empty; var platformSpecificOperations = PooledConcurrentDictionary<KeyValuePair<IOperation, ISymbol>, SmallDictionary<string, PlatformAttributes>>.GetInstance(); >>>>>>> var osPlatformTypeArray = osPlatformType != null ? ImmutableArray.Create(osPlatformType) : ImmutableArray<INamedTypeSymbol>.Empty; var platformSpecificOperations = PooledConcurrentDictionary<KeyValuePair<IOperation, ISymbol>, (SmallDictionary<string, PlatformAttributes> attributes, SmallDictionary<string, PlatformAttributes>? csAttributes)>.GetInstance(); <<<<<<< ReportDiagnostics(platformSpecificOperation, pair.attributes, csAttributes, context, platformSpecificMembers); ======= ReportDiagnostics(platformSpecificOperation, attributes, context); >>>>>>> ReportDiagnostics(platformSpecificOperation, pair.attributes, csAttributes, context, platformSpecificMembers); <<<<<<< private static void ReportDiagnosticsForAll(PooledConcurrentDictionary<IOperation, (SmallDictionary<string, PlatformAttributes> attributes, SmallDictionary<string, PlatformAttributes>? csAttributes)> platformSpecificOperations, OperationBlockAnalysisContext context, ConcurrentDictionary<ISymbol, SmallDictionary<string, PlatformAttributes>?> platformSpecificMembers) ======= private static void ReportDiagnosticsForAll(PooledConcurrentDictionary<KeyValuePair<IOperation, ISymbol>, SmallDictionary<string, PlatformAttributes>> platformSpecificOperations, OperationBlockAnalysisContext context) >>>>>>> private static void ReportDiagnosticsForAll(PooledConcurrentDictionary<KeyValuePair<IOperation, ISymbol>, (SmallDictionary<string, PlatformAttributes> attributes, SmallDictionary<string, PlatformAttributes>? csAttributes)> platformSpecificOperations, OperationBlockAnalysisContext context, ConcurrentDictionary<ISymbol, SmallDictionary<string, PlatformAttributes>?> platformSpecificMembers) <<<<<<< static ISymbol GetAccessorMethod(ConcurrentDictionary<ISymbol, SmallDictionary<string, PlatformAttributes>?> platformSpecificMembers, ISymbol symbol, IEnumerable<ISymbol> accessors) { foreach (var accessor in accessors) { if (accessor != null && platformSpecificMembers.TryGetValue(accessor, out var attribute) && attribute != null) { return accessor; } } return symbol; } static bool HasSameVersionedPlatformSupport(SmallDictionary<string, PlatformAttributes> attributes, string pName, bool checkSupport) { if (attributes.TryGetValue(pName, out var attribute)) { var version = attribute.UnsupportedSecond ?? attribute.UnsupportedFirst; if (checkSupport) { var supportedVersion = attribute.SupportedSecond ?? attribute.SupportedFirst; if (supportedVersion != null) { version = version == null || supportedVersion >= version ? supportedVersion : version; } else { version = supportedVersion; } } if (version != null && !IsEmptyVersion(version)) { return true; } } return false; } } private enum Callsite { AllPlatforms, Reachable, Unreachable ======= >>>>>>> static bool HasSameVersionedPlatformSupport(SmallDictionary<string, PlatformAttributes> attributes, string pName, bool checkSupport) { if (attributes.TryGetValue(pName, out var attribute)) { var version = attribute.UnsupportedSecond ?? attribute.UnsupportedFirst; if (checkSupport) { var supportedVersion = attribute.SupportedSecond ?? attribute.SupportedFirst; if (supportedVersion != null) { version = version == null || supportedVersion >= version ? supportedVersion : version; } else { version = supportedVersion; } } if (version != null && !IsEmptyVersion(version)) { return true; } } return false; } } private enum Callsite { AllPlatforms, Reachable, Unreachable <<<<<<< private static void AnalyzeOperation(IOperation operation, OperationAnalysisContext context, PooledConcurrentDictionary<IOperation, (SmallDictionary<string, PlatformAttributes> attributes, SmallDictionary<string, PlatformAttributes>? csAttributes)> platformSpecificOperations, ======= private static void AnalyzeOperation(IOperation operation, OperationAnalysisContext context, PooledConcurrentDictionary<KeyValuePair<IOperation, ISymbol>, SmallDictionary<string, PlatformAttributes>> platformSpecificOperations, >>>>>>> private static void AnalyzeOperation(IOperation operation, OperationAnalysisContext context, PooledConcurrentDictionary<KeyValuePair<IOperation, ISymbol>, (SmallDictionary<string, PlatformAttributes> attributes, SmallDictionary<string, PlatformAttributes>? csAttributes)> platformSpecificOperations, <<<<<<< static void CheckOperationAttributes(IOperation operation, OperationAnalysisContext context, PooledConcurrentDictionary<IOperation, (SmallDictionary<string, PlatformAttributes> attributes, SmallDictionary<string, PlatformAttributes>? csAttributes)> platformSpecificOperations, ConcurrentDictionary<ISymbol, SmallDictionary<string, PlatformAttributes>?> platformSpecificMembers, ImmutableArray<string> msBuildPlatforms, ISymbol symbol) ======= static void CheckOperationAttributes(IOperation operation, OperationAnalysisContext context, PooledConcurrentDictionary<KeyValuePair<IOperation, ISymbol>, SmallDictionary<string, PlatformAttributes>> platformSpecificOperations, ConcurrentDictionary<ISymbol, SmallDictionary<string, PlatformAttributes>?> platformSpecificMembers, ImmutableArray<string> msBuildPlatforms, ISymbol symbol, bool checkParents) >>>>>>> static void CheckOperationAttributes(IOperation operation, OperationAnalysisContext context, PooledConcurrentDictionary<KeyValuePair<IOperation, ISymbol>, (SmallDictionary<string, PlatformAttributes> attributes, SmallDictionary<string, PlatformAttributes>? csAttributes)> platformSpecificOperations, ConcurrentDictionary<ISymbol, SmallDictionary<string, PlatformAttributes>?> platformSpecificMembers, ImmutableArray<string> msBuildPlatforms, ISymbol symbol, bool checkParents) <<<<<<< platformSpecificOperations.TryAdd(operation, (notSuppressedAttributes, callSiteAttributes)); ======= platformSpecificOperations.TryAdd(new KeyValuePair<IOperation, ISymbol>(operation, symbol), notSuppressedAttributes); >>>>>>> platformSpecificOperations.TryAdd(new KeyValuePair<IOperation, ISymbol>(operation, symbol), (notSuppressedAttributes, callSiteAttributes)); <<<<<<< platformSpecificOperations.TryAdd(operation, (copiedAttributes, null)); ======= platformSpecificOperations.TryAdd(new KeyValuePair<IOperation, ISymbol>(operation, symbol), copiedAttributes); >>>>>>> platformSpecificOperations.TryAdd(new KeyValuePair<IOperation, ISymbol>(operation, symbol), (copiedAttributes, null));
<<<<<<< private static readonly MetadataReference SystemCollectionsImmutableReference = MetadataReference.CreateFromAssembly(typeof(ImmutableArray).Assembly); ======= >>>>>>> private static readonly MetadataReference SystemCollectionsImmutableReference = MetadataReference.CreateFromAssembly(typeof(ImmutableArray).Assembly);
<<<<<<< private static readonly Lazy<Assembly> s_netstandardAssembly = new Lazy<Assembly>(() => Assembly.Load("netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")); private static readonly Lazy<MetadataReference> s_netstandardReference = new Lazy<MetadataReference>(() => MetadataReference.CreateFromFile(s_netstandardAssembly.Value.Location)); ======= public static readonly MetadataReference SystemComponentModelCompositionReference = MetadataReference.CreateFromFile(typeof(System.ComponentModel.Composition.ExportAttribute).Assembly.Location); public static readonly MetadataReference SystemCompositionReference = MetadataReference.CreateFromFile(typeof(System.Composition.ExportAttribute).Assembly.Location); >>>>>>> private static readonly Lazy<Assembly> s_netstandardAssembly = new Lazy<Assembly>(() => Assembly.Load("netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")); private static readonly Lazy<MetadataReference> s_netstandardReference = new Lazy<MetadataReference>(() => MetadataReference.CreateFromFile(s_netstandardAssembly.Value.Location)); public static readonly MetadataReference SystemComponentModelCompositionReference = MetadataReference.CreateFromFile(typeof(System.ComponentModel.Composition.ExportAttribute).Assembly.Location); public static readonly MetadataReference SystemCompositionReference = MetadataReference.CreateFromFile(typeof(System.Composition.ExportAttribute).Assembly.Location); <<<<<<< ======= internal static readonly MetadataReference SystemWebExtensions = MetadataReference.CreateFromFile(typeof(System.Web.Script.Serialization.JavaScriptSerializer).Assembly.Location); internal static readonly MetadataReference SystemGlobalization = MetadataReference.CreateFromFile(Assembly.Load("System.Globalization, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a").Location); >>>>>>> internal static readonly MetadataReference SystemWebExtensions = MetadataReference.CreateFromFile(typeof(System.Web.Script.Serialization.JavaScriptSerializer).Assembly.Location);
<<<<<<< public const string SystemConvert = "System.Convert"; public const string SystemSecurityCryptographySymmetricAlgorithm = "System.Security.Cryptography.SymmetricAlgorithm"; ======= public const string NewtonsoftJsonTypeNameHandling = "Newtonsoft.Json.TypeNameHandling"; >>>>>>> public const string SystemConvert = "System.Convert"; public const string SystemSecurityCryptographySymmetricAlgorithm = "System.Security.Cryptography.SymmetricAlgorithm"; public const string NewtonsoftJsonTypeNameHandling = "Newtonsoft.Json.TypeNameHandling";
<<<<<<< var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(compilationContext.Compilation); INamedTypeSymbol cancellationTokenType = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingCancellationToken); INamedTypeSymbol iprogressType = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIProgress1); if (cancellationTokenType == null) ======= INamedTypeSymbol? cancellationTokenType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingCancellationToken); if (cancellationTokenType != null) >>>>>>> var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(compilationContext.Compilation); INamedTypeSymbol? cancellationTokenType = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingCancellationToken); INamedTypeSymbol? iprogressType = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIProgress1); if (cancellationTokenType == null)
<<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitUsing(IUsingOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitUsing(IUsingOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitUsing(IUsingOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitWhileLoop(IWhileLoopOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitWhileLoop(IWhileLoopOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitWhileLoop(IWhileLoopOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitForEachLoop(IForEachLoopOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitForEachLoop(IForEachLoopOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitForEachLoop(IForEachLoopOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitForLoop(IForLoopOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitForLoop(IForLoopOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitForLoop(IForLoopOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitForToLoop(IForToLoopOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitForToLoop(IForToLoopOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitForToLoop(IForToLoopOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitCoalesce(ICoalesceOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitCoalesce(ICoalesceOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitCoalesce(ICoalesceOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitConditional(IConditionalOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitConditional(IConditionalOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitConditional(IConditionalOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitConditionalAccess(IConditionalAccessOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitConditionalAccess(IConditionalAccessOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitConditionalAccess(IConditionalAccessOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitThrow(IThrowOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitThrow(IThrowOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitThrow(IThrowOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitTry(ITryOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitTry(ITryOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitTry(ITryOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitCatchClause(ICatchClauseOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitCatchClause(ICatchClauseOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitCatchClause(ICatchClauseOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public override TAbstractAnalysisValue VisitLock(ILockOperation operation, object argument) ======= public override TAbstractAnalysisValue VisitLock(ILockOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public override TAbstractAnalysisValue VisitLock(ILockOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitBranch(IBranchOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitBranch(IBranchOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitBranch(IBranchOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitLabeled(ILabeledOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitLabeled(ILabeledOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitLabeled(ILabeledOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitSwitch(ISwitchOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitSwitch(ISwitchOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitSwitch(ISwitchOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitSwitchCase(ISwitchCaseOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitSwitchCase(ISwitchCaseOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitSwitchCase(ISwitchCaseOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitDefaultCaseClause(IDefaultCaseClauseOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitDefaultCaseClause(IDefaultCaseClauseOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitDefaultCaseClause(IDefaultCaseClauseOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitPatternCaseClause(IPatternCaseClauseOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitPatternCaseClause(IPatternCaseClauseOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitPatternCaseClause(IPatternCaseClauseOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitRangeCaseClause(IRangeCaseClauseOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitRangeCaseClause(IRangeCaseClauseOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitRangeCaseClause(IRangeCaseClauseOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitRelationalCaseClause(IRelationalCaseClauseOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitRelationalCaseClause(IRelationalCaseClauseOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitRelationalCaseClause(IRelationalCaseClauseOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitMemberInitializer(IMemberInitializerOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitMemberInitializer(IMemberInitializerOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitMemberInitializer(IMemberInitializerOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitBlock(IBlockOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitBlock(IBlockOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitBlock(IBlockOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitVariableInitializer(IVariableInitializerOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitVariableInitializer(IVariableInitializerOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitVariableInitializer(IVariableInitializerOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitFieldInitializer(IFieldInitializerOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitFieldInitializer(IFieldInitializerOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitFieldInitializer(IFieldInitializerOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitParameterInitializer(IParameterInitializerOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitParameterInitializer(IParameterInitializerOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitParameterInitializer(IParameterInitializerOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitPropertyInitializer(IPropertyInitializerOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitPropertyInitializer(IPropertyInitializerOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitPropertyInitializer(IPropertyInitializerOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitEnd(IEndOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitEnd(IEndOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitEnd(IEndOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitEmpty(IEmptyOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitEmpty(IEmptyOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitEmpty(IEmptyOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitNameOf(INameOfOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitNameOf(INameOfOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitNameOf(INameOfOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitAnonymousFunction(IAnonymousFunctionOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitAnonymousFunction(IAnonymousFunctionOperation operation, object? argument) >>>>>>> public sealed override TAbstractAnalysisValue VisitAnonymousFunction(IAnonymousFunctionOperation operation, object? argument) <<<<<<< [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitLocalFunction(ILocalFunctionOperation operation, object argument) ======= public sealed override TAbstractAnalysisValue VisitLocalFunction(ILocalFunctionOperation operation, object? argument) >>>>>>> [ExcludeFromCodeCoverage] public sealed override TAbstractAnalysisValue VisitLocalFunction(ILocalFunctionOperation operation, object? argument)
<<<<<<< public const string SystemSecurityCryptographyRSA = "System.Security.Cryptography.RSA"; public const string SystemSecurityCryptographyDSA = "System.Security.Cryptography.DSA"; public const string SystemSecurityCryptographyAsymmetricAlgorithm = "System.Security.Cryptography.AsymmetricAlgorithm"; public const string SystemSecurityCryptographyCryptoConfig = "System.Security.Cryptography.CryptoConfig"; ======= public const string SystemSecurityCryptographyX509CertificatesX509Store = "System.Security.Cryptography.X509Certificates.X509Store"; public const string SystemSecurityCryptographyX509CertificatesStoreName = "System.Security.Cryptography.X509Certificates.StoreName"; >>>>>>> public const string SystemSecurityCryptographyX509CertificatesX509Store = "System.Security.Cryptography.X509Certificates.X509Store"; public const string SystemSecurityCryptographyX509CertificatesStoreName = "System.Security.Cryptography.X509Certificates.StoreName"; public const string SystemSecurityCryptographyRSA = "System.Security.Cryptography.RSA"; public const string SystemSecurityCryptographyDSA = "System.Security.Cryptography.DSA"; public const string SystemSecurityCryptographyAsymmetricAlgorithm = "System.Security.Cryptography.AsymmetricAlgorithm"; public const string SystemSecurityCryptographyCryptoConfig = "System.Security.Cryptography.CryptoConfig";
<<<<<<< internal static DiagnosticDescriptor MissingIdRule = new DiagnosticDescriptor( id: MissingId, title: "The analyzer is missing a diagnostic id", messageFormat: "The analyzer '{0}' is missing a diagnostic id", category: "Syntax", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); ======= internal static DiagnosticDescriptor MissingIdRule = CreateRule(MissingId, "You are missing a diagnostic id", "You are missing a diagnostic id"); >>>>>>> internal static DiagnosticDescriptor MissingIdRule = CreateRule(MissingId, "The analyzer is missing a diagnostic id", "The analyzer '{0}' is missing a diagnostic id"); <<<<<<< internal static DiagnosticDescriptor MissingInitRule = new DiagnosticDescriptor( id: MissingInit, title: "The analyzer is missing the required Initialize method", messageFormat: "The analyzer '{0}' is missing the required Initialize method", category: "Syntax", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); ======= internal static DiagnosticDescriptor MissingInitRule = CreateRule(MissingInit, "You are missing the required Initialize method", "You are missing the required Initialize method"); >>>>>>> internal static DiagnosticDescriptor MissingInitRule = CreateRule(MissingInit, "The analyzer is missing the required Initialize method", "The analyzer '{0}' is missing the required Initialize method"); <<<<<<< internal static DiagnosticDescriptor MissingRegisterRule = new DiagnosticDescriptor( id: MissingRegisterStatement, title: "An action must be registered within the method", messageFormat: "An action must be registered within the '{0}' method", category: "Syntax", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); ======= internal static DiagnosticDescriptor MissingRegisterRule = CreateRule(MissingRegisterStatement, "You need to register an action within the Initialize method", "You need to register an action within the Initialize method"); >>>>>>> internal static DiagnosticDescriptor MissingRegisterRule = CreateRule(MissingRegisterStatement, "An action must be registered within the method", "An action must be registered within the '{0}' method"); <<<<<<< internal static DiagnosticDescriptor SupportedRulesRule = new DiagnosticDescriptor( id: SupportedRules, title: "The immutable array should contain every DiagnosticDescriptor rule that was created", messageFormat: "The immutable array should contain every DiagnosticDescriptor rule that was created", category: "Syntax", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); ======= internal static DiagnosticDescriptor SupportedRulesRule = CreateRule(SupportedRules, "The immutable array should contain every DiagnosticDescriptor rule that was created", "The immutable array should contain every DiagnosticDescriptor rule that was created"); #endregion #region analysis rules public const string MissingAnalysisMethod = "MetaAnalyzer018"; internal static DiagnosticDescriptor MissingAnalysisMethodRule = CreateRule(MissingAnalysisMethod, "Missing analysis method", "You are missing the method that was registered to perform the analysis"); #endregion #region analysis for IfStatement rules public const string IfStatementMissing = "MetaAnalyzer024"; internal static DiagnosticDescriptor IfStatementMissingRule = CreateRule(IfStatementMissing, "Missing 1st step", "The first step is to extract the if statement from {0}"); public const string IfStatementIncorrect = "MetaAnalyzer022"; internal static DiagnosticDescriptor IfStatementIncorrectRule = CreateRule(IfStatementIncorrect, "If statement extraction incorrect", "This statement should extract the if statement in question by casting {0}.Node to IfStatementSyntax"); public const string IfKeywordMissing = "MetaAnalyzer021"; internal static DiagnosticDescriptor IfKeywordMissingRule = CreateRule(IfKeywordMissing, "Missing 2nd step", "The second step is to extract the 'if' keyword from {0}"); public const string IfKeywordIncorrect = "MetaAnalyzer025"; internal static DiagnosticDescriptor IfKeywordIncorrectRule = CreateRule(IfKeywordIncorrect, "Incorrect 2nd step", "This statement should extract the 'if' keyword from {0}"); public const string TrailingTriviaCheckMissing = "MetaAnalyzer026"; internal static DiagnosticDescriptor TrailingTriviaCheckMissingRule = CreateRule(TrailingTriviaCheckMissing, "Missing 3rd step", "The third step is to begin looking for the space between 'if' and '(' by checking if {0} has trailing trivia"); public const string TrailingTriviaCheckIncorrect = "MetaAnalyzer027"; internal static DiagnosticDescriptor TrailingTriviaCheckIncorrectRule = CreateRule(TrailingTriviaCheckIncorrect, "Incorrect 3rd step", "This statement should be an if statement that checks to see if {0} has trailing trivia"); public const string TrailingTriviaVarMissing = "MetaAnalyzer028"; internal static DiagnosticDescriptor TrailingTriviaVarMissingRule = CreateRule(TrailingTriviaVarMissing, "Missing 4th step", "The fourth step is to extract the last trailing trivia of {0} into a variable"); public const string TrailingTriviaVarIncorrect = "MetaAnalyzer029"; internal static DiagnosticDescriptor TrailingTriviaVarIncorrectRule = CreateRule(TrailingTriviaVarIncorrect, "Incorrect 4th step", "This statement should extract the last trailing trivia of {0} into a variable"); >>>>>>> internal static DiagnosticDescriptor SupportedRulesRule = CreateRule(SupportedRules, "The immutable array should contain every DiagnosticDescriptor rule that was created", "The immutable array should contain every DiagnosticDescriptor rule that was created"); #endregion #region analysis rules public const string MissingAnalysisMethod = "MetaAnalyzer018"; internal static DiagnosticDescriptor MissingAnalysisMethodRule = CreateRule(MissingAnalysisMethod, "Missing analysis method", "You are missing the method that was registered to perform the analysis"); #endregion #region analysis for IfStatement rules public const string IfStatementMissing = "MetaAnalyzer024"; internal static DiagnosticDescriptor IfStatementMissingRule = CreateRule(IfStatementMissing, "Missing 1st step", "The first step is to extract the if statement from {0}"); public const string IfStatementIncorrect = "MetaAnalyzer022"; internal static DiagnosticDescriptor IfStatementIncorrectRule = CreateRule(IfStatementIncorrect, "If statement extraction incorrect", "This statement should extract the if statement in question by casting {0}.Node to IfStatementSyntax"); public const string IfKeywordMissing = "MetaAnalyzer021"; internal static DiagnosticDescriptor IfKeywordMissingRule = CreateRule(IfKeywordMissing, "Missing 2nd step", "The second step is to extract the 'if' keyword from {0}"); public const string IfKeywordIncorrect = "MetaAnalyzer025"; internal static DiagnosticDescriptor IfKeywordIncorrectRule = CreateRule(IfKeywordIncorrect, "Incorrect 2nd step", "This statement should extract the 'if' keyword from {0}"); public const string TrailingTriviaCheckMissing = "MetaAnalyzer026"; internal static DiagnosticDescriptor TrailingTriviaCheckMissingRule = CreateRule(TrailingTriviaCheckMissing, "Missing 3rd step", "The third step is to begin looking for the space between 'if' and '(' by checking if {0} has trailing trivia"); public const string TrailingTriviaCheckIncorrect = "MetaAnalyzer027"; internal static DiagnosticDescriptor TrailingTriviaCheckIncorrectRule = CreateRule(TrailingTriviaCheckIncorrect, "Incorrect 3rd step", "This statement should be an if statement that checks to see if {0} has trailing trivia"); public const string TrailingTriviaVarMissing = "MetaAnalyzer028"; internal static DiagnosticDescriptor TrailingTriviaVarMissingRule = CreateRule(TrailingTriviaVarMissing, "Missing 4th step", "The fourth step is to extract the last trailing trivia of {0} into a variable"); public const string TrailingTriviaVarIncorrect = "MetaAnalyzer029"; internal static DiagnosticDescriptor TrailingTriviaVarIncorrectRule = CreateRule(TrailingTriviaVarIncorrect, "Incorrect 4th step", "This statement should extract the last trailing trivia of {0} into a variable");
<<<<<<< case StartActionKind.CompilationStartAction: arg2 = "Initialize"; break; case StartActionKind.CodeBlockStartAction: case StartActionKind.OperationBlockStartAction: arg2 = "Initialize, CompilationStartAction"; break; default: throw new ArgumentException("Unsupported action kind", nameof(kind)); } return new[] { parameterName, arg2 }; ======= StartActionKind.CompilationStartAction => "Initialize", StartActionKind.CodeBlockStartAction or StartActionKind.OperationBlockStartAction => "Initialize, CompilationStartAction", _ => throw new ArgumentException("Unsupported action kind", nameof(kind)), }; string message = string.Format(CodeAnalysisDiagnosticsResources.StartActionWithNoRegisteredActionsMessage, parameterName, arg2); string fileName = language == LanguageNames.CSharp ? "Test0.cs" : "Test0.vb"; return new DiagnosticResult(DiagnosticIds.StartActionWithNoRegisteredActionsRuleId, DiagnosticSeverity.Warning) .WithLocation(fileName, line, column) .WithMessageFormat(message); >>>>>>> StartActionKind.CompilationStartAction => "Initialize", StartActionKind.CodeBlockStartAction or StartActionKind.OperationBlockStartAction => "Initialize, CompilationStartAction", _ => throw new ArgumentException("Unsupported action kind", nameof(kind)), }; return new[] { parameterName, arg2 };
<<<<<<< public const string SystemEventArgs = "System.EventArgs"; ======= public const string SystemXmlSchemaXmlSchemaCollection = "System.Xml.Schema.XmlSchemaCollection"; >>>>>>> public const string SystemEventArgs = "System.EventArgs"; public const string SystemXmlSchemaXmlSchemaCollection = "System.Xml.Schema.XmlSchemaCollection";
<<<<<<< case "op_Addition": case "op_AdditonAssignment": return createSingle("Add"); case "op_BitwiseAnd": case "op_BitwiseAndAssignment": return createSingle("BitwiseAnd"); case "op_BitwiseOr": case "op_BitwiseOrAssignment": return createSingle("BitwiseOr"); case "op_Decrement": return createSingle("Decrement"); case "op_Division": case "op_DivisionAssignment": return createSingle("Divide"); case "op_Equality": case "op_Inequality": return createSingle("Equals"); case "op_ExclusiveOr": case "op_ExclusiveOrAssignment": return createSingle("Xor"); case "op_GreaterThan": case "op_GreaterThanOrEqual": case "op_LessThan": case "op_LessThanOrEqual": return new ExpectedAlternateMethodGroup(alternateMethod1: "CompareTo", alternateMethod2: "Compare"); case "op_Increment": return createSingle("Increment"); case "op_LeftShift": case "op_LeftShiftAssignment": return createSingle("LeftShift"); case "op_LogicalAnd": return createSingle("LogicalAnd"); case "op_LogicalOr": return createSingle("LogicalOr"); case "op_LogicalNot": return createSingle("LogicalNot"); case "op_Modulus": case "op_ModulusAssignment": return new ExpectedAlternateMethodGroup(alternateMethod1: "Mod", alternateMethod2: "Remainder"); case "op_MultiplicationAssignment": case "op_Multiply": return createSingle("Multiply"); case "op_OnesComplement": return createSingle("OnesComplement"); case "op_RightShift": case "op_RightShiftAssignment": case "op_SignedRightShift": case "op_UnsignedRightShift": case "op_UnsignedRightShiftAssignment": return createSingle("RightShift"); case "op_Subtraction": case "op_SubtractionAssignment": return createSingle("Subtract"); case "op_UnaryNegation": return createSingle("Negate"); case "op_UnaryPlus": return createSingle("Plus"); case "op_Implicit": case "op_Explicit": return new ExpectedAlternateMethodGroup(alternateMethod1: $"To{GetTypeName(returnType)}", alternateMethod2: parameterType != null ? $"From{GetTypeName(parameterType)}" : null); default: return null; } static string GetTypeName(ITypeSymbol typeSymbol) { if (typeSymbol.TypeKind != TypeKind.Array) { return typeSymbol.Name; } var elementType = typeSymbol; do { elementType = ((IArrayTypeSymbol)elementType).ElementType; } while (elementType.TypeKind == TypeKind.Array); return elementType.Name + "Array"; } ======= "op_Addition" or "op_AdditonAssignment" => createSingle("Add"), "op_BitwiseAnd" or "op_BitwiseAndAssignment" => createSingle("BitwiseAnd"), "op_BitwiseOr" or "op_BitwiseOrAssignment" => createSingle("BitwiseOr"), "op_Decrement" => createSingle("Decrement"), "op_Division" or "op_DivisionAssignment" => createSingle("Divide"), "op_Equality" or "op_Inequality" => createSingle("Equals"), "op_ExclusiveOr" or "op_ExclusiveOrAssignment" => createSingle("Xor"), "op_GreaterThan" or "op_GreaterThanOrEqual" or "op_LessThan" or "op_LessThanOrEqual" => new ExpectedAlternateMethodGroup(alternateMethod1: "CompareTo", alternateMethod2: "Compare"), "op_Increment" => createSingle("Increment"), "op_LeftShift" or "op_LeftShiftAssignment" => createSingle("LeftShift"), "op_LogicalAnd" => createSingle("LogicalAnd"), "op_LogicalOr" => createSingle("LogicalOr"), "op_LogicalNot" => createSingle("LogicalNot"), "op_Modulus" or "op_ModulusAssignment" => new ExpectedAlternateMethodGroup(alternateMethod1: "Mod", alternateMethod2: "Remainder"), "op_MultiplicationAssignment" or "op_Multiply" => createSingle("Multiply"), "op_OnesComplement" => createSingle("OnesComplement"), "op_RightShift" or "op_RightShiftAssignment" or "op_SignedRightShift" or "op_UnsignedRightShift" or "op_UnsignedRightShiftAssignment" => createSingle("RightShift"), "op_Subtraction" or "op_SubtractionAssignment" => createSingle("Subtract"), "op_UnaryNegation" => createSingle("Negate"), "op_UnaryPlus" => createSingle("Plus"), "op_Implicit" or "op_Explicit" => new ExpectedAlternateMethodGroup(alternateMethod1: $"To{returnType.Name}", alternateMethod2: parameterType != null ? $"From{parameterType.Name}" : null), _ => null, }; >>>>>>> "op_Addition" or "op_AdditonAssignment" => createSingle("Add"), "op_BitwiseAnd" or "op_BitwiseAndAssignment" => createSingle("BitwiseAnd"), "op_BitwiseOr" or "op_BitwiseOrAssignment" => createSingle("BitwiseOr"), "op_Decrement" => createSingle("Decrement"), "op_Division" or "op_DivisionAssignment" => createSingle("Divide"), "op_Equality" or "op_Inequality" => createSingle("Equals"), "op_ExclusiveOr" or "op_ExclusiveOrAssignment" => createSingle("Xor"), "op_GreaterThan" or "op_GreaterThanOrEqual" or "op_LessThan" or "op_LessThanOrEqual" => new ExpectedAlternateMethodGroup(alternateMethod1: "CompareTo", alternateMethod2: "Compare"), "op_Increment" => createSingle("Increment"), "op_LeftShift" or "op_LeftShiftAssignment" => createSingle("LeftShift"), "op_LogicalAnd" => createSingle("LogicalAnd"), "op_LogicalOr" => createSingle("LogicalOr"), "op_LogicalNot" => createSingle("LogicalNot"), "op_Modulus" or "op_ModulusAssignment" => new ExpectedAlternateMethodGroup(alternateMethod1: "Mod", alternateMethod2: "Remainder"), "op_MultiplicationAssignment" or "op_Multiply" => createSingle("Multiply"), "op_OnesComplement" => createSingle("OnesComplement"), "op_RightShift" or "op_RightShiftAssignment" or "op_SignedRightShift" or "op_UnsignedRightShift" or "op_UnsignedRightShiftAssignment" => createSingle("RightShift"), "op_Subtraction" or "op_SubtractionAssignment" => createSingle("Subtract"), "op_UnaryNegation" => createSingle("Negate"), "op_UnaryPlus" => createSingle("Plus"), "op_Implicit" or "op_Explicit" => new ExpectedAlternateMethodGroup(alternateMethod1: $"To{GetTypeName(returnType)}", alternateMethod2: parameterType != null ? $"From{GetTypeName(parameterType)}" : null), _ => null, }; static string GetTypeName(ITypeSymbol typeSymbol) { if (typeSymbol.TypeKind != TypeKind.Array) { return typeSymbol.Name; } var elementType = typeSymbol; do { elementType = ((IArrayTypeSymbol)elementType).ElementType; } while (elementType.TypeKind == TypeKind.Array); return elementType.Name + "Array"; }
<<<<<<< targetAnalysisData.SetAbstactValueForEntities(newValue, entityBeingAssigned: null); ======= newValue = newValue.WithEntitiesRemoved(entitiesToExclude); >>>>>>> newValue = newValue.WithEntitiesRemoved(entitiesToExclude); <<<<<<< var entitiesToFilterBuilder = PooledHashSet<AnalysisEntity>.GetInstance(); var copyValue = returnValueAndPredicateKind.Value.Value; ======= using var entitiesToFilterBuilder = PooledHashSet<AnalysisEntity>.GetInstance(); var copyValue = returnValueAndPredicateKindOpt.Value.Value; >>>>>>> using var entitiesToFilterBuilder = PooledHashSet<AnalysisEntity>.GetInstance(); var copyValue = returnValueAndPredicateKind.Value.Value; <<<<<<< if (entitiesToFilterBuilder.Count > 0) { copyValue = entitiesToFilterBuilder.Count == copyValueEntities.Count ? CopyAbstractValue.Unknown : copyValue.WithEntitiesRemoved(entitiesToFilterBuilder); } return (copyValue, returnValueAndPredicateKind.Value.PredicateValueKind); ======= >>>>>>> <<<<<<< if (processedEntities.Add(entity)) { var copyValue = GetAbstractValue(entity); analysisData.SetAbstactValueForEntities(copyValue, entityBeingAssigned: null); processedEntities.AddRange(copyValue.AnalysisEntities); } ======= var copyValue = GetAbstractValue(entity); analysisData.SetAbstactValueForEntities(copyValue, entityBeingAssignedOpt: null); processedEntities.AddRange(copyValue.AnalysisEntities); >>>>>>> var copyValue = GetAbstractValue(entity); analysisData.SetAbstactValueForEntities(copyValue, entityBeingAssigned: null); processedEntities.AddRange(copyValue.AnalysisEntities);
<<<<<<< public const string MicrosoftAspNetCoreMvcFiltersFilterCollection = "Microsoft.AspNetCore.Mvc.Filters.FilterCollection"; public const string MicrosoftAspNetCoreMvcController = "Microsoft.AspNetCore.Mvc.Controller"; public const string MicrosoftAspNetCoreMvcControllerBase = "Microsoft.AspNetCore.Mvc.ControllerBase"; public const string MicrosoftAspNetCoreMvcNonActionAttribute = "Microsoft.AspNetCore.Mvc.NonActionAttribute"; public const string MicrosoftAspNetCoreMvcHttpPostAttribute = "Microsoft.AspNetCore.Mvc.HttpPostAttribute"; public const string MicrosoftAspNetCoreMvcHttpPutAttribute = "Microsoft.AspNetCore.Mvc.HttpPutAttribute"; public const string MicrosoftAspNetCoreMvcHttpDeleteAttribute = "Microsoft.AspNetCore.Mvc.HttpDeleteAttribute"; public const string MicrosoftAspNetCoreMvcHttpPatchAttribute = "Microsoft.AspNetCore.Mvc.HttpPatchAttribute"; public const string MicrosoftAspNetCoreMvcFiltersIFilterMetadata = "Microsoft.AspNetCore.Mvc.Filters.IFilterMetadata"; public const string MicrosoftAspNetCoreAntiforgeryIAntiforgery = "Microsoft.AspNetCore.Antiforgery.IAntiforgery"; public const string MicrosoftAspNetCoreMvcFiltersIAsyncAuthorizationFilter = "Microsoft.AspNetCore.Mvc.Filters.IAsyncAuthorizationFilter"; public const string MicrosoftAspNetCoreMvcFiltersAuthorizationFilterContext = "Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext"; ======= public const string NewtonsoftJsonTypeNameHandling = "Newtonsoft.Json.TypeNameHandling"; >>>>>>> public const string MicrosoftAspNetCoreMvcFiltersFilterCollection = "Microsoft.AspNetCore.Mvc.Filters.FilterCollection"; public const string MicrosoftAspNetCoreMvcController = "Microsoft.AspNetCore.Mvc.Controller"; public const string MicrosoftAspNetCoreMvcControllerBase = "Microsoft.AspNetCore.Mvc.ControllerBase"; public const string MicrosoftAspNetCoreMvcNonActionAttribute = "Microsoft.AspNetCore.Mvc.NonActionAttribute"; public const string MicrosoftAspNetCoreMvcHttpPostAttribute = "Microsoft.AspNetCore.Mvc.HttpPostAttribute"; public const string MicrosoftAspNetCoreMvcHttpPutAttribute = "Microsoft.AspNetCore.Mvc.HttpPutAttribute"; public const string MicrosoftAspNetCoreMvcHttpDeleteAttribute = "Microsoft.AspNetCore.Mvc.HttpDeleteAttribute"; public const string MicrosoftAspNetCoreMvcHttpPatchAttribute = "Microsoft.AspNetCore.Mvc.HttpPatchAttribute"; public const string MicrosoftAspNetCoreMvcFiltersIFilterMetadata = "Microsoft.AspNetCore.Mvc.Filters.IFilterMetadata"; public const string MicrosoftAspNetCoreAntiforgeryIAntiforgery = "Microsoft.AspNetCore.Antiforgery.IAntiforgery"; public const string MicrosoftAspNetCoreMvcFiltersIAsyncAuthorizationFilter = "Microsoft.AspNetCore.Mvc.Filters.IAsyncAuthorizationFilter"; public const string MicrosoftAspNetCoreMvcFiltersAuthorizationFilterContext = "Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext"; public const string NewtonsoftJsonTypeNameHandling = "Newtonsoft.Json.TypeNameHandling";
<<<<<<< [Theory, WorkItem(4149, "https://github.com/dotnet/roslyn-analyzers/issues/4149")] [InlineData("")] [InlineData("dotnet_code_quality.exclude_structs = true")] [InlineData("dotnet_code_quality.exclude_structs = false")] [InlineData("dotnet_code_quality.CA1051.exclude_structs = true")] [InlineData("dotnet_code_quality.CA1051.exclude_structs = false")] public async Task PublicFieldOnStruct_AnalyzerOption(string editorConfigText) { var expectsIssue = !editorConfigText.EndsWith("true", StringComparison.OrdinalIgnoreCase); var csharpCode = @" public struct S { public int " + (expectsIssue ? "[|F|]" : "F") + @"; }"; await new VerifyCS.Test { TestState = { Sources = { csharpCode }, AdditionalFiles = { (".editorconfig", editorConfigText) } } }.RunAsync(); var vbCode = @" Public Structure S Public " + (expectsIssue ? "[|F|]" : "F") + @" As Integer End Structure"; await new VerifyVB.Test { TestState = { Sources = { vbCode }, AdditionalFiles = { (".editorconfig", editorConfigText) } } }.RunAsync(); } ======= [Fact, WorkItem(4149, "https://github.com/dotnet/roslyn-analyzers/issues/4149")] public async Task TypeWithStructLayoutAttribute_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public class C { public int F; } [StructLayout(LayoutKind.Sequential)] public struct S { public int F; }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System.Runtime.InteropServices <StructLayout(LayoutKind.Sequential)> Public Class C Public F As Integer End Class <StructLayout(LayoutKind.Sequential)> Public Structure S Public F As Integer End Structure"); } >>>>>>> [Fact, WorkItem(4149, "https://github.com/dotnet/roslyn-analyzers/issues/4149")] public async Task TypeWithStructLayoutAttribute_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public class C { public int F; } [StructLayout(LayoutKind.Sequential)] public struct S { public int F; }"); await VerifyVB.VerifyAnalyzerAsync(@" Imports System.Runtime.InteropServices <StructLayout(LayoutKind.Sequential)> Public Class C Public F As Integer End Class <StructLayout(LayoutKind.Sequential)> Public Structure S Public F As Integer End Structure"); } [Theory, WorkItem(4149, "https://github.com/dotnet/roslyn-analyzers/issues/4149")] [InlineData("")] [InlineData("dotnet_code_quality.exclude_structs = true")] [InlineData("dotnet_code_quality.exclude_structs = false")] [InlineData("dotnet_code_quality.CA1051.exclude_structs = true")] [InlineData("dotnet_code_quality.CA1051.exclude_structs = false")] public async Task PublicFieldOnStruct_AnalyzerOption(string editorConfigText) { var expectsIssue = !editorConfigText.EndsWith("true", StringComparison.OrdinalIgnoreCase); var csharpCode = @" public struct S { public int " + (expectsIssue ? "[|F|]" : "F") + @"; }"; await new VerifyCS.Test { TestState = { Sources = { csharpCode }, AdditionalFiles = { (".editorconfig", editorConfigText) } } }.RunAsync(); var vbCode = @" Public Structure S Public " + (expectsIssue ? "[|F|]" : "F") + @" As Integer End Structure"; await new VerifyVB.Test { TestState = { Sources = { vbCode }, AdditionalFiles = { (".editorconfig", editorConfigText) } } }.RunAsync(); }
<<<<<<< SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested; var frame = GetFrame(); if (frame != null) { frame.Navigating += OnFrameNavigating; } ======= if (DesignMode.DesignModeEnabled == false) { SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested; } >>>>>>> if (DesignMode.DesignModeEnabled == false) { SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested; var frame = GetFrame(); if (frame != null) { frame.Navigating += OnFrameNavigating; } } <<<<<<< SystemNavigationManager.GetForCurrentView().BackRequested -= OnBackRequested; var frame = GetFrame(); if (frame != null) { frame.Navigating -= OnFrameNavigating; } ======= if (DesignMode.DesignModeEnabled == false) { SystemNavigationManager.GetForCurrentView().BackRequested -= OnBackRequested; } >>>>>>> if (DesignMode.DesignModeEnabled == false) { SystemNavigationManager.GetForCurrentView().BackRequested -= OnBackRequested; var frame = GetFrame(); if (frame != null) { frame.Navigating -= OnFrameNavigating; } }
<<<<<<< [Fact] [WorkItem(2746, "https://github.com/dotnet/roslyn-analyzers/issues/2746")] public void DisposableObject_FieldAsOutArgument_NotDisposed_NoDiagnostic() { var editorConfigFile = GetEditorConfigFileToDisableInterproceduralAnalysis(DisposeAnalysisKind.AllPaths); VerifyCSharp(@" using System; class A : IDisposable { public void Dispose() { } } class B : IDisposable { private A _a; public bool Flag; public void M() { TryCreate(out _a); } private void TryCreate(out A a) { a = Flag ? new A() : null; } public void Dispose() { _a?.Dispose(); } }", editorConfigFile); } [Fact] [WorkItem(2746, "https://github.com/dotnet/roslyn-analyzers/issues/2746")] public void DisposableObject_FieldAsRefArgument_NotDisposed_NoDiagnostic() { var editorConfigFile = GetEditorConfigFileToDisableInterproceduralAnalysis(DisposeAnalysisKind.AllPaths); VerifyCSharp(@" using System; class A : IDisposable { public void Dispose() { } } class B : IDisposable { private A _a; public bool Flag; public void M() { TryCreate(ref _a); } private void TryCreate(ref A a) { a = Flag ? new A() : null; } public void Dispose() { _a?.Dispose(); } }", editorConfigFile); } [Fact] [WorkItem(2681, "https://github.com/dotnet/roslyn-analyzers/issues/2681")] public void DisposableObject_InterlockedAssignmentToField_NotDisposed_NoDiagnostic() { var editorConfigFile = GetEditorConfigFileToDisableInterproceduralAnalysis(DisposeAnalysisKind.AllPaths); VerifyCSharp(@" using System; using System.Threading; class CustomDisposable : IDisposable { public void Dispose() { } } class Test { private CustomDisposable field1; private void NoWarning() { field1 = new CustomDisposable(); } private void Warning1() { var temp = new CustomDisposable(); Interlocked.Exchange(ref field1, temp)?.Dispose(); } private void Warning2() { var temp = new CustomDisposable(); Interlocked.CompareExchange(ref field1, temp, null); } }", editorConfigFile); } ======= [Fact] [WorkItem(2782, "https://github.com/dotnet/roslyn-analyzers/issues/2782")] public void DisposableObject_CoalesceAssignment_NotDisposed_Diagnostic() { VerifyCSharp(@" using System.Collections.Generic; using System.IO; namespace ConsoleApp1 { class Program { static void Main(string[] args) { } internal void RunDotNetNewAsync( string fileName, IDictionary<string, string> environmentVariables = null) { environmentVariables ??= new Dictionary<string, string>(); var f = File.Open(fileName, FileMode.Open); } } }", parseOptions: new CSharpParseOptions(CSharpLanguageVersion.CSharp8), expected: // Test0.cs(18,21): warning CA2000: Call System.IDisposable.Dispose on object created by 'File.Open(fileName, FileMode.Open)' before all references to it are out of scope. GetCSharpResultAt(18, 21, "File.Open(fileName, FileMode.Open)")); } [Fact] [WorkItem(2782, "https://github.com/dotnet/roslyn-analyzers/issues/2782")] public void DisposableObject_CoalesceAssignment_NotDisposed_Diagnostic_02() { VerifyCSharp(@" using System.Collections.Generic; using System.IO; namespace ConsoleApp1 { class Program { static void Main(string[] args) { } internal void RunDotNetNewAsync( string fileName, FileStream f = null) { f ??= File.Open(fileName, FileMode.Open); } } }", parseOptions: new CSharpParseOptions(CSharpLanguageVersion.CSharp8), expected: // Test0.cs(17,19): warning CA2000: Call System.IDisposable.Dispose on object created by 'File.Open(fileName, FileMode.Open)' before all references to it are out of scope. GetCSharpResultAt(17, 19, "File.Open(fileName, FileMode.Open)")); } >>>>>>> [WorkItem(2782, "https://github.com/dotnet/roslyn-analyzers/issues/2782")] public void DisposableObject_CoalesceAssignment_NotDisposed_Diagnostic() { VerifyCSharp(@" using System.Collections.Generic; using System.IO; namespace ConsoleApp1 { class Program { static void Main(string[] args) { } internal void RunDotNetNewAsync( string fileName, IDictionary<string, string> environmentVariables = null) { environmentVariables ??= new Dictionary<string, string>(); var f = File.Open(fileName, FileMode.Open); } } }", parseOptions: new CSharpParseOptions(CSharpLanguageVersion.CSharp8), expected: // Test0.cs(18,21): warning CA2000: Call System.IDisposable.Dispose on object created by 'File.Open(fileName, FileMode.Open)' before all references to it are out of scope. GetCSharpResultAt(18, 21, "File.Open(fileName, FileMode.Open)")); } [Fact] [WorkItem(2782, "https://github.com/dotnet/roslyn-analyzers/issues/2782")] public void DisposableObject_CoalesceAssignment_NotDisposed_Diagnostic_02() { VerifyCSharp(@" using System.Collections.Generic; using System.IO; namespace ConsoleApp1 { class Program { static void Main(string[] args) { } internal void RunDotNetNewAsync( string fileName, FileStream f = null) { f ??= File.Open(fileName, FileMode.Open); } } }", parseOptions: new CSharpParseOptions(CSharpLanguageVersion.CSharp8), expected: // Test0.cs(17,19): warning CA2000: Call System.IDisposable.Dispose on object created by 'File.Open(fileName, FileMode.Open)' before all references to it are out of scope. GetCSharpResultAt(17, 19, "File.Open(fileName, FileMode.Open)")); } [Fact] [WorkItem(2746, "https://github.com/dotnet/roslyn-analyzers/issues/2746")] public void DisposableObject_FieldAsOutArgument_NotDisposed_NoDiagnostic() { var editorConfigFile = GetEditorConfigFileToDisableInterproceduralAnalysis(DisposeAnalysisKind.AllPaths); VerifyCSharp(@" using System; class A : IDisposable { public void Dispose() { } } class B : IDisposable { private A _a; public bool Flag; public void M() { TryCreate(out _a); } private void TryCreate(out A a) { a = Flag ? new A() : null; } public void Dispose() { _a?.Dispose(); } }", editorConfigFile); } [Fact] [WorkItem(2746, "https://github.com/dotnet/roslyn-analyzers/issues/2746")] public void DisposableObject_FieldAsRefArgument_NotDisposed_NoDiagnostic() { var editorConfigFile = GetEditorConfigFileToDisableInterproceduralAnalysis(DisposeAnalysisKind.AllPaths); VerifyCSharp(@" using System; class A : IDisposable { public void Dispose() { } } class B : IDisposable { private A _a; public bool Flag; public void M() { TryCreate(ref _a); } private void TryCreate(ref A a) { a = Flag ? new A() : null; } public void Dispose() { _a?.Dispose(); } }", editorConfigFile); } [Fact] [WorkItem(2681, "https://github.com/dotnet/roslyn-analyzers/issues/2681")] public void DisposableObject_InterlockedAssignmentToField_NotDisposed_NoDiagnostic() { var editorConfigFile = GetEditorConfigFileToDisableInterproceduralAnalysis(DisposeAnalysisKind.AllPaths); VerifyCSharp(@" using System; using System.Threading; class CustomDisposable : IDisposable { public void Dispose() { } } class Test { private CustomDisposable field1; private void NoWarning() { field1 = new CustomDisposable(); } private void Warning1() { var temp = new CustomDisposable(); Interlocked.Exchange(ref field1, temp)?.Dispose(); } private void Warning2() { var temp = new CustomDisposable(); Interlocked.CompareExchange(ref field1, temp, null); } }", editorConfigFile); }
<<<<<<< if (appliedImportingConstructorAttribute.ApplicationSyntaxReference != null) { // '{0}' is MEF-exported and should have a single importing constructor of the correct form context.ReportDiagnostic(Diagnostic.Create(Rule, appliedImportingConstructorAttribute.ApplicationSyntaxReference.GetSyntax(context.CancellationToken).GetLocation(), ScenarioProperties.NonPublicConstructor, namedType.Name)); } ======= // '{0}' is MEF-exported and should have a single importing constructor of the correct form context.ReportDiagnostic( appliedImportingConstructorAttribute.ApplicationSyntaxReference.CreateDiagnostic( Rule, ScenarioProperties.NonPublicConstructor, context.CancellationToken, namedType.Name)); >>>>>>> if (appliedImportingConstructorAttribute.ApplicationSyntaxReference != null) { // '{0}' is MEF-exported and should have a single importing constructor of the correct form context.ReportDiagnostic( appliedImportingConstructorAttribute.ApplicationSyntaxReference.CreateDiagnostic( Rule, ScenarioProperties.NonPublicConstructor, context.CancellationToken, namedType.Name)); }
<<<<<<< ReportDiagnostic(context, MissingInitRule, _analyzerClassSymbol.Locations[0], _analyzerClassSymbol.Name.ToString()); return new CheckInitializeInfo(); ======= ReportDiagnostic(context, MissingInitRule, _analyzerClassSymbol.Locations[0], _analyzerClassSymbol.Name); return new List<object>(new object[] { registerCall, registerArgs }); >>>>>>> ReportDiagnostic(context, MissingInitRule, _analyzerClassSymbol.Locations[0], _analyzerClassSymbol.Name); return new CheckInitializeInfo(); <<<<<<< ReportDiagnostic(context, MissingRegisterRule, _initializeSymbol.Locations[0], _initializeSymbol.Name.ToString()); return new CheckInitializeInfo(); ======= ReportDiagnostic(context, MissingRegisterRule, _initializeSymbol.Locations[0], _initializeSymbol.Name); return new List<object>(new object[] { registerCall, registerArgs, invocExpr }); >>>>>>> ReportDiagnostic(context, MissingRegisterRule, _initializeSymbol.Locations[0], _initializeSymbol.Name); return new CheckInitializeInfo(); <<<<<<< ReportDiagnostic(context, InvalidStatementRule, statement.GetLocation(), statement.ToString()); return new CheckInitializeInfo(); ======= ReportDiagnostic(context, InvalidStatementRule, statement.GetLocation()); return new List<object>(new object[] { registerCall, registerArgs, invocExpr }); >>>>>>> ReportDiagnostic(context, InvalidStatementRule, statement.GetLocation()); return new CheckInitializeInfo(); <<<<<<< ReportDiagnostic(context, InvalidStatementRule, statement.GetLocation(), statement.ToString()); return new CheckInitializeInfo(); ======= ReportDiagnostic(context, InvalidStatementRule, statement.GetLocation()); return new List<object>(new object[] { registerCall, registerArgs, invocExpr }); >>>>>>> ReportDiagnostic(context, InvalidStatementRule, statement.GetLocation()); return new CheckInitializeInfo(); <<<<<<< ReportDiagnostic(context, InvalidStatementRule, statement.GetLocation(), statement.ToString()); return new CheckInitializeInfo(); ======= ReportDiagnostic(context, InvalidStatementRule, statement.GetLocation()); return new List<object>(new object[] { registerCall, registerArgs, invocExpr }); >>>>>>> ReportDiagnostic(context, InvalidStatementRule, statement.GetLocation()); return new CheckInitializeInfo(); <<<<<<< ReportDiagnostic(context, InvalidStatementRule, statement.GetLocation(), statement.ToString()); return new CheckInitializeInfo(); ======= ReportDiagnostic(context, InvalidStatementRule, statement.GetLocation()); return new List<object>(new object[] { registerCall, registerArgs, invocExpr }); >>>>>>> ReportDiagnostic(context, InvalidStatementRule, statement.GetLocation()); return new CheckInitializeInfo(); <<<<<<< ReportDiagnostic(context, InvalidStatementRule, statement.GetLocation(), statement.ToString()); return new CheckInitializeInfo(); ======= ReportDiagnostic(context, InvalidStatementRule, statement.GetLocation()); return new List<object>(new object[] { registerCall, registerArgs, invocExpr }); >>>>>>> ReportDiagnostic(context, InvalidStatementRule, statement.GetLocation()); return new CheckInitializeInfo(); <<<<<<< ReportDiagnostic(context, TooManyInitStatementsRule, _initializeSymbol.Locations[0], _initializeSymbol.Name.ToString()); return new CheckInitializeInfo(); ======= ReportDiagnostic(context, TooManyInitStatementsRule, _initializeSymbol.Locations[0], _initializeSymbol.Name); return new List<object>(new object[] { registerCall, registerArgs, invocExpr }); >>>>>>> ReportDiagnostic(context, TooManyInitStatementsRule, _initializeSymbol.Locations[0], _initializeSymbol.Name); return new CheckInitializeInfo();
<<<<<<< public const string SystemTextEncoding = "System.Text.Encoding"; public const string SystemSecurityCryptographyAesGcm = "System.Security.Cryptography.AesGcm"; public const string SystemSecurityCryptographyAesCcm = "System.Security.Cryptography.AesCcm"; ======= public const string MicrosoftAspNetCoreRazorHostingRazorCompiledItemAttribute = "Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute"; >>>>>>> public const string MicrosoftAspNetCoreRazorHostingRazorCompiledItemAttribute = "Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute"; public const string SystemTextEncoding = "System.Text.Encoding"; public const string SystemSecurityCryptographyAesGcm = "System.Security.Cryptography.AesGcm"; public const string SystemSecurityCryptographyAesCcm = "System.Security.Cryptography.AesCcm";
<<<<<<< using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; ======= using System.Net; >>>>>>> using System; using System.Collections.Immutable; using System.Net; using Microsoft.CodeAnalysis; <<<<<<< internal static readonly ImmutableDictionary<string, ReportDiagnostic> NullableWarnings = GetNullableWarningsFromCompiler(); ======= static Test() { // If we have outdated defaults from the host unit test application targeting an older .NET Framework, use more // reasonable TLS protocol version for outgoing connections. #pragma warning disable CA5364 // Do Not Use Deprecated Security Protocols if (ServicePointManager.SecurityProtocol == (SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls)) #pragma warning restore CA5364 // Do Not Use Deprecated Security Protocols { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; } } >>>>>>> static Test() { // If we have outdated defaults from the host unit test application targeting an older .NET Framework, use more // reasonable TLS protocol version for outgoing connections. #pragma warning disable CA5364 // Do Not Use Deprecated Security Protocols #pragma warning disable CS0618 // Type or member is obsolete if (ServicePointManager.SecurityProtocol == (SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls)) #pragma warning restore CS0618 // Type or member is obsolete #pragma warning restore CA5364 // Do Not Use Deprecated Security Protocols { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; } } internal static readonly ImmutableDictionary<string, ReportDiagnostic> NullableWarnings = GetNullableWarningsFromCompiler();
<<<<<<< public const string SystemRandom = "System.Random"; ======= public const string SystemNetServicePointManager = "System.Net.ServicePointManager"; >>>>>>> public const string SystemNetServicePointManager = "System.Net.ServicePointManager"; public const string SystemRandom = "System.Random";
<<<<<<< await MetricsHelper.ComputeCoupledTypesAndComplexityExcludingMemberDeclsAsync(declarations, property, coupledTypesBuilder, context).ConfigureAwait(false); MetricsHelper.AddCoupledNamedTypes(coupledTypesBuilder, property.Parameters); MetricsHelper.AddCoupledNamedTypes(coupledTypesBuilder, property.Type); ======= await MetricsHelper.ComputeCoupledTypesAndComplexityExcludingMemberDeclsAsync(declarations, property, coupledTypesBuilder, semanticModelProvider, cancellationToken).ConfigureAwait(false); MetricsHelper.AddCoupledNamedTypes(coupledTypesBuilder, wellKnownTypeProvider, property.Parameters); MetricsHelper.AddCoupledNamedTypes(coupledTypesBuilder, wellKnownTypeProvider, property.Type); >>>>>>> await MetricsHelper.ComputeCoupledTypesAndComplexityExcludingMemberDeclsAsync(declarations, property, coupledTypesBuilder, context).ConfigureAwait(false); MetricsHelper.AddCoupledNamedTypes(coupledTypesBuilder, wellKnownTypeProvider, property.Parameters); MetricsHelper.AddCoupledNamedTypes(coupledTypesBuilder, wellKnownTypeProvider, property.Type);
<<<<<<< LocalM(); if (OperatingSystemHelper.IsOSPlatformVersionAtLeast(""Windows"", 10, 2)) ======= if (OperatingSystem.IsOSPlatformVersionAtLeast(""Windows"", 10, 2)) >>>>>>> LocalM(); if (OperatingSystem.IsOSPlatformVersionAtLeast(""Windows"", 10, 2)) <<<<<<< [|WindowsOnlyMethod()|]; if (OperatingSystemHelper.IsOSPlatformVersionAtLeast(""Windows"", 10, 2)) ======= if (suppressed) { WindowsOnlyMethod(); } else { [|WindowsOnlyMethod()|]; } if (OperatingSystem.IsOSPlatformVersionAtLeast(""Windows"", 10, 2)) >>>>>>> [|WindowsOnlyMethod()|]; if (OperatingSystem.IsOSPlatformVersionAtLeast(""Windows"", 10, 2))
<<<<<<< => options.GetSymbolNamesOption(EditorConfigOptionNames.NullCheckValidationMethods, rule, compilation, cancellationToken, namePrefixOpt: "M:"); ======= => options.GetSymbolNamesWithValueOption<Unit>(EditorConfigOptionNames.NullCheckValidationMethods, namePrefixOpt: "M:", rule, compilation, cancellationToken); >>>>>>> => options.GetSymbolNamesWithValueOption(EditorConfigOptionNames.NullCheckValidationMethods, rule, compilation, cancellationToken, namePrefixOpt: "M:"); <<<<<<< => options.GetSymbolNamesOption(EditorConfigOptionNames.AdditionalStringFormattingMethods, rule, compilation, cancellationToken, namePrefixOpt: "M:"); ======= => options.GetSymbolNamesWithValueOption<Unit>(EditorConfigOptionNames.AdditionalStringFormattingMethods, namePrefixOpt: "M:", rule, compilation, cancellationToken); >>>>>>> => options.GetSymbolNamesOption(EditorConfigOptionNames.AdditionalStringFormattingMethods, rule, compilation, cancellationToken, namePrefixOpt: "M:"); <<<<<<< => options.GetSymbolNamesOption(EditorConfigOptionNames.ExcludedSymbolNames, rule, compilation, cancellationToken); ======= => options.GetSymbolNamesWithValueOption<Unit>(EditorConfigOptionNames.ExcludedSymbolNames, namePrefixOpt: null, rule, compilation, cancellationToken); >>>>>>> => options.GetSymbolNamesWithValueOption(EditorConfigOptionNames.ExcludedSymbolNames, rule, compilation, cancellationToken); <<<<<<< => options.GetSymbolNamesOption(EditorConfigOptionNames.ExcludedTypeNamesWithDerivedTypes, rule, compilation, cancellationToken, namePrefixOpt: "T:"); ======= => options.GetSymbolNamesWithValueOption<Unit>(EditorConfigOptionNames.ExcludedTypeNamesWithDerivedTypes, namePrefixOpt: "T:", rule, compilation, cancellationToken); >>>>>>> => options.GetSymbolNamesWithValueOption(EditorConfigOptionNames.ExcludedTypeNamesWithDerivedTypes, rule, compilation, cancellationToken, namePrefixOpt: "T:"); <<<<<<< => options.GetSymbolNamesOption(EditorConfigOptionNames.DisallowedSymbolNames, rule, compilation, cancellationToken); ======= => options.GetSymbolNamesWithValueOption<Unit>(EditorConfigOptionNames.DisallowedSymbolNames, namePrefixOpt: null, rule, compilation, cancellationToken); >>>>>>> => options.GetSymbolNamesWithValueOption(EditorConfigOptionNames.DisallowedSymbolNames, rule, compilation, cancellationToken); <<<<<<< return options.GetSymbolNamesOption(EditorConfigOptionNames.AdditionalRequiredSuffixes, rule, compilation, cancellationToken, namePrefixOpt: "T:", getTypeAndSuffixFunc: GetParts); ======= return options.GetSymbolNamesWithValueOption(EditorConfigOptionNames.AdditionalRequiredSuffixes, namePrefixOpt: "T:", rule, compilation, cancellationToken, GetParts); >>>>>>> return options.GetSymbolNamesWithValueOption(EditorConfigOptionNames.AdditionalRequiredSuffixes, rule, compilation, cancellationToken, namePrefixOpt: "T:", getTypeAndSuffixFunc: GetParts); <<<<<<< public static SymbolNamesOption GetInheritanceExcludedSymbolNamesOption( this AnalyzerOptions options, DiagnosticDescriptor rule, Compilation compilation, CancellationToken cancellationToken) => options.GetSymbolNamesOption(EditorConfigOptionNames.AdditionalInheritanceExcludedSymbolNames, rule, compilation, cancellationToken, optionForcedValue: "N:System.*"); private static SymbolNamesOption GetSymbolNamesOption( ======= public static SymbolNamesWithValueOption<INamedTypeSymbol> GetAdditionalRequiredGenericInterfaces( this AnalyzerOptions options, DiagnosticDescriptor rule, Compilation compilation, CancellationToken cancellationToken) { return options.GetSymbolNamesWithValueOption(EditorConfigOptionNames.AdditionalRequiredGenericInterfaces, namePrefixOpt: "T:", rule, compilation, cancellationToken, x => GetParts(x, compilation)); static SymbolNamesWithValueOption<INamedTypeSymbol>.NameParts GetParts(string name, Compilation compilation) { var split = name.Split(new[] { "->" }, StringSplitOptions.RemoveEmptyEntries); // If we don't find exactly one '->', we assume that there is no given suffix. if (split.Length != 2) { return new SymbolNamesWithValueOption<INamedTypeSymbol>.NameParts(name); } var genericInterfaceFullName = split[1].Trim(); if (!genericInterfaceFullName.StartsWith("T:", StringComparison.Ordinal)) { genericInterfaceFullName = $"T:{genericInterfaceFullName}"; } var matchingSymbols = DocumentationCommentId.GetSymbolsForDeclarationId(genericInterfaceFullName, compilation); if (matchingSymbols.Length != 1 || !(matchingSymbols[0] is INamedTypeSymbol namedType) || namedType.TypeKind != TypeKind.Interface || !namedType.IsGenericType) { // Invalid matching type so we assume there was no associated type return new SymbolNamesWithValueOption<INamedTypeSymbol>.NameParts(split[0]); } return new SymbolNamesWithValueOption<INamedTypeSymbol>.NameParts(split[0], namedType); } } private static SymbolNamesWithValueOption<TValue> GetSymbolNamesWithValueOption<TValue>( >>>>>>> public static SymbolNamesWithValueOption<INamedTypeSymbol> GetAdditionalRequiredGenericInterfaces( this AnalyzerOptions options, DiagnosticDescriptor rule, Compilation compilation, CancellationToken cancellationToken) { return options.GetSymbolNamesWithValueOption(EditorConfigOptionNames.AdditionalRequiredGenericInterfaces, namePrefixOpt: "T:", rule, compilation, cancellationToken, x => GetParts(x, compilation)); static SymbolNamesWithValueOption<INamedTypeSymbol>.NameParts GetParts(string name, Compilation compilation) { var split = name.Split(new[] { "->" }, StringSplitOptions.RemoveEmptyEntries); // If we don't find exactly one '->', we assume that there is no given suffix. if (split.Length != 2) { return new SymbolNamesWithValueOption<INamedTypeSymbol>.NameParts(name); } var genericInterfaceFullName = split[1].Trim(); if (!genericInterfaceFullName.StartsWith("T:", StringComparison.Ordinal)) { genericInterfaceFullName = $"T:{genericInterfaceFullName}"; } var matchingSymbols = DocumentationCommentId.GetSymbolsForDeclarationId(genericInterfaceFullName, compilation); if (matchingSymbols.Length != 1 || !(matchingSymbols[0] is INamedTypeSymbol namedType) || namedType.TypeKind != TypeKind.Interface || !namedType.IsGenericType) { // Invalid matching type so we assume there was no associated type return new SymbolNamesWithValueOption<INamedTypeSymbol>.NameParts(split[0]); } return new SymbolNamesWithValueOption<INamedTypeSymbol>.NameParts(split[0], namedType); } } public static SymbolNamesWithValueOption<Unit> GetInheritanceExcludedSymbolNamesOption( this AnalyzerOptions options, DiagnosticDescriptor rule, Compilation compilation, CancellationToken cancellationToken) => options.GetSymbolNamesOption(EditorConfigOptionNames.AdditionalInheritanceExcludedSymbolNames, rule, compilation, cancellationToken, optionForcedValue: "N:System.*"); private static SymbolNamesWithValueOption<TValue> GetSymbolNamesWithValueOption<TValue>( <<<<<<< var names = optionValue.Split('|').ToImmutableArray(); option = SymbolNamesOption.Create(names, compilation, namePrefixOpt, getTypeAndSuffixFunc); ======= var names = s.Split('|').ToImmutableArray(); option = SymbolNamesWithValueOption<TValue>.Create(names, compilation, namePrefixOpt, getTypeAndSuffixFunc); >>>>>>> var names = optionValue.Split('|').ToImmutableArray(); option = SymbolNamesWithValueOption<TValue>.Create(names, compilation, namePrefixOpt, getTypeAndSuffixFunc);
<<<<<<< public static readonly DiagnosticDescriptor EqualityRule = new DiagnosticDescriptor( ======= public static readonly DiagnosticDescriptor Rule = new( >>>>>>> public static readonly DiagnosticDescriptor EqualityRule = new(
<<<<<<< public const string DefaultableTypeShouldHaveDefaultableFieldsRuleId = "RS0040"; ======= public const string RelaxTestNamingSuppressionRuleId = "RS0039"; >>>>>>> public const string RelaxTestNamingSuppressionRuleId = "RS0039"; public const string DefaultableTypeShouldHaveDefaultableFieldsRuleId = "RS0040";
<<<<<<< using System.Threading.Tasks; ======= // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; >>>>>>> // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks;
<<<<<<< internal static DiagnosticDescriptor RuleNoArguments = new DiagnosticDescriptor(RuleId, ======= internal static DiagnosticDescriptor Descriptor = DiagnosticDescriptorHelper.Create(RuleId, >>>>>>> internal static DiagnosticDescriptor RuleNoArguments = DiagnosticDescriptorHelper.Create(RuleId, <<<<<<< helpLinkUri: HelpUri, customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule); internal static DiagnosticDescriptor RuleIncorrectMessage = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageIncorrectMessage, DiagnosticCategory.Usage, DiagnosticHelpers.DefaultDiagnosticSeverity, isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX, description: s_localizableDescription, helpLinkUri: HelpUri, customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule); internal static DiagnosticDescriptor RuleIncorrectParameterName = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageIncorrectParameterName, DiagnosticCategory.Usage, DiagnosticHelpers.DefaultDiagnosticSeverity, isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX, description: s_localizableDescription, helpLinkUri: HelpUri, customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(RuleNoArguments, RuleIncorrectMessage, RuleIncorrectParameterName); ======= isPortedFxCopRule: true, isDataflowRule: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); >>>>>>> helpLinkUri: HelpUri, customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(RuleNoArguments, RuleIncorrectMessage, RuleIncorrectParameterName);
<<<<<<< private static readonly MetadataReference s_corlibReference = MetadataReference.CreateFromFile(typeof(object).Assembly.Location); private static readonly MetadataReference s_systemCoreReference = MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location); private static readonly MetadataReference s_systemXmlReference = MetadataReference.CreateFromFile(typeof(System.Xml.XmlDocument).Assembly.Location); private static readonly MetadataReference s_systemXmlDataReference = MetadataReference.CreateFromFile(typeof(System.Data.Rule).Assembly.Location); private static readonly MetadataReference s_csharpSymbolsReference = MetadataReference.CreateFromFile(typeof(CSharpCompilation).Assembly.Location); private static readonly MetadataReference s_visualBasicSymbolsReference = MetadataReference.CreateFromFile(typeof(VisualBasicCompilation).Assembly.Location); private static readonly MetadataReference s_visualBasicReference = MetadataReference.CreateFromFile(typeof(Microsoft.VisualBasic.Devices.ComputerInfo).Assembly.Location); private static readonly MetadataReference s_codeAnalysisReference = MetadataReference.CreateFromFile(typeof(Compilation).Assembly.Location); private static readonly MetadataReference s_workspacesReference = MetadataReference.CreateFromFile(typeof(Workspace).Assembly.Location); private static readonly MetadataReference s_immutableCollectionsReference = MetadataReference.CreateFromFile(typeof(ImmutableArray<int>).Assembly.Location); private static readonly MetadataReference s_systemDiagnosticsDebugReference = MetadataReference.CreateFromFile(typeof(Debug).Assembly.Location); private static readonly MetadataReference s_systemDataReference = MetadataReference.CreateFromFile(typeof(System.Data.DataSet).Assembly.Location); private static readonly MetadataReference s_systemWebReference = MetadataReference.CreateFromFile(typeof(System.Web.HttpRequest).Assembly.Location); private static readonly MetadataReference s_systemRuntimeSerialization = MetadataReference.CreateFromFile(typeof(System.Runtime.Serialization.NetDataContractSerializer).Assembly.Location); private static readonly MetadataReference s_testReferenceAssembly = MetadataReference.CreateFromFile(typeof(OtherDll.OtherDllStaticMethods).Assembly.Location); private static readonly MetadataReference s_systemXmlLinq = MetadataReference.CreateFromFile(typeof(System.Xml.Linq.XAttribute).Assembly.Location); ======= >>>>>>> <<<<<<< .AddMetadataReference(projectId, s_corlibReference) .AddMetadataReference(projectId, s_systemCoreReference) .AddMetadataReference(projectId, s_systemXmlReference) .AddMetadataReference(projectId, s_codeAnalysisReference) .AddMetadataReference(projectId, SystemRuntimeFacadeRef) .AddMetadataReference(projectId, SystemThreadingFacadeRef) .AddMetadataReference(projectId, SystemThreadingTaskFacadeRef) .AddMetadataReference(projectId, s_workspacesReference) .AddMetadataReference(projectId, s_systemDiagnosticsDebugReference) .AddMetadataReference(projectId, s_systemWebReference) .AddMetadataReference(projectId, s_systemXmlLinq) .AddMetadataReference(projectId, s_systemRuntimeSerialization) ======= .AddMetadataReference(projectId, MetadataReferences.CorlibReference) .AddMetadataReference(projectId, MetadataReferences.SystemCoreReference) .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemXmlReference) .AddMetadataReference(projectId, MetadataReferences.CodeAnalysisReference) .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemRuntimeFacadeRef) .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemThreadingFacadeRef) .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemThreadingTaskFacadeRef) .AddMetadataReference(projectId, AdditionalMetadataReferences.WorkspacesReference) .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemDiagnosticsDebugReference) >>>>>>> .AddMetadataReference(projectId, MetadataReferences.CorlibReference) .AddMetadataReference(projectId, MetadataReferences.SystemCoreReference) .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemXmlReference) .AddMetadataReference(projectId, MetadataReferences.CodeAnalysisReference) .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemRuntimeFacadeRef) .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemThreadingFacadeRef) .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemThreadingTaskFacadeRef) .AddMetadataReference(projectId, AdditionalMetadataReferences.WorkspacesReference) .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemDiagnosticsDebugReference) .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemWebReference) .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemXmlLinq) .AddMetadataReference(projectId, AdditionalMetadataReferences.SystemRuntimeSerialization)
<<<<<<< private static readonly ConditionalWeakTable<AnalyzerOptions, ICategorizedAnalyzerConfigOptions> s_cachedOptions = new ConditionalWeakTable<AnalyzerOptions, ICategorizedAnalyzerConfigOptions>(); ======= private static readonly ConditionalWeakTable<AnalyzerOptions, CategorizedAnalyzerConfigOptions> s_cachedOptions = new(); >>>>>>> private static readonly ConditionalWeakTable<AnalyzerOptions, ICategorizedAnalyzerConfigOptions> s_cachedOptions = new(); <<<<<<< MSBuildItemOptionNamesHelpers.VerifySupportedItemOptionName(itemOptionName); // MSBuild property values should be set at compilation level, and cannot have different values per-tree. // So, we default to first syntax tree. if (compilation.SyntaxTrees.FirstOrDefault() is not { } tree) { return ImmutableArray<string>.Empty; } var propertyOptionName = MSBuildItemOptionNamesHelpers.GetPropertyNameForItemOptionName(itemOptionName); var analyzerConfigOptions = options.GetOrComputeCategorizedAnalyzerConfigOptions(compilation, cancellationToken); var propertyValue = analyzerConfigOptions.GetOptionValue(propertyOptionName, tree, rule: null, tryParseValue: (string value, out string? result) => { result = value; return true; }, defaultValue: null, OptionKind.BuildProperty); return MSBuildItemOptionNamesHelpers.ParseItemOptionValue(propertyValue); } /// <summary> /// Returns true if the given source symbol has required visibility based on options: /// 1. If user has explicitly configured candidate <see cref="SymbolVisibilityGroup"/> in editor config options and /// given symbol's visibility is one of the candidate visibilities. /// 2. Otherwise, if user has not configured visibility, and given symbol's visibility /// matches the given default symbol visibility. /// </summary> public static bool MatchesConfiguredVisibility( this AnalyzerOptions options, DiagnosticDescriptor rule, ISymbol symbol, Compilation compilation, CancellationToken cancellationToken, SymbolVisibilityGroup defaultRequiredVisibility = SymbolVisibilityGroup.Public) => options.MatchesConfiguredVisibility(rule, symbol, symbol, compilation, cancellationToken, defaultRequiredVisibility); /// <summary> /// Returns true if the given symbol has required visibility based on options in context of the given containing symbol: /// 1. If user has explicitly configured candidate <see cref="SymbolVisibilityGroup"/> in editor config options and /// given symbol's visibility is one of the candidate visibilities. /// 2. Otherwise, if user has not configured visibility, and given symbol's visibility /// matches the given default symbol visibility. /// </summary> public static bool MatchesConfiguredVisibility( this AnalyzerOptions options, DiagnosticDescriptor rule, ISymbol symbol, ISymbol containingContextSymbol, Compilation compilation, CancellationToken cancellationToken, SymbolVisibilityGroup defaultRequiredVisibility = SymbolVisibilityGroup.Public) { var allowedVisibilities = options.GetSymbolVisibilityGroupOption(rule, containingContextSymbol, compilation, defaultRequiredVisibility, cancellationToken); return allowedVisibilities == SymbolVisibilityGroup.All || allowedVisibilities.Contains(symbol.GetResultantVisibility()); } /// <summary> /// Returns true if the given symbol has required symbol modifiers based on options: /// 1. If user has explicitly configured candidate <see cref="SymbolModifiers"/> in editor config options and /// given symbol has all the required modifiers. /// 2. Otherwise, if user has not configured modifiers. /// </summary> public static bool MatchesConfiguredModifiers( this AnalyzerOptions options, DiagnosticDescriptor rule, ISymbol symbol, Compilation compilation, CancellationToken cancellationToken, SymbolModifiers defaultRequiredModifiers = SymbolModifiers.None) { var requiredModifiers = options.GetRequiredModifiersOption(rule, symbol, compilation, defaultRequiredModifiers, cancellationToken); return symbol.GetSymbolModifiers().Contains(requiredModifiers); } #pragma warning disable CA1801 // Review unused parameters - 'compilation' is used conditionally. private static ICategorizedAnalyzerConfigOptions GetOrComputeCategorizedAnalyzerConfigOptions( this AnalyzerOptions options, Compilation compilation, CancellationToken cancellationToken) #pragma warning restore CA1801 // Review unused parameters { // TryGetValue upfront to avoid allocating createValueCallback if the entry already exists. ======= // TryGetValue upfront to avoid allocating createValueCallback if the entry already exists. >>>>>>> MSBuildItemOptionNamesHelpers.VerifySupportedItemOptionName(itemOptionName); // MSBuild property values should be set at compilation level, and cannot have different values per-tree. // So, we default to first syntax tree. if (compilation.SyntaxTrees.FirstOrDefault() is not { } tree) { return ImmutableArray<string>.Empty; } var propertyOptionName = MSBuildItemOptionNamesHelpers.GetPropertyNameForItemOptionName(itemOptionName); var analyzerConfigOptions = options.GetOrComputeCategorizedAnalyzerConfigOptions(compilation, cancellationToken); var propertyValue = analyzerConfigOptions.GetOptionValue(propertyOptionName, tree, rule: null, tryParseValue: (string value, out string? result) => { result = value; return true; }, defaultValue: null, OptionKind.BuildProperty); return MSBuildItemOptionNamesHelpers.ParseItemOptionValue(propertyValue); } /// <summary> /// Returns true if the given source symbol has required visibility based on options: /// 1. If user has explicitly configured candidate <see cref="SymbolVisibilityGroup"/> in editor config options and /// given symbol's visibility is one of the candidate visibilities. /// 2. Otherwise, if user has not configured visibility, and given symbol's visibility /// matches the given default symbol visibility. /// </summary> public static bool MatchesConfiguredVisibility( this AnalyzerOptions options, DiagnosticDescriptor rule, ISymbol symbol, Compilation compilation, CancellationToken cancellationToken, SymbolVisibilityGroup defaultRequiredVisibility = SymbolVisibilityGroup.Public) => options.MatchesConfiguredVisibility(rule, symbol, symbol, compilation, cancellationToken, defaultRequiredVisibility); /// <summary> /// Returns true if the given symbol has required visibility based on options in context of the given containing symbol: /// 1. If user has explicitly configured candidate <see cref="SymbolVisibilityGroup"/> in editor config options and /// given symbol's visibility is one of the candidate visibilities. /// 2. Otherwise, if user has not configured visibility, and given symbol's visibility /// matches the given default symbol visibility. /// </summary> public static bool MatchesConfiguredVisibility( this AnalyzerOptions options, DiagnosticDescriptor rule, ISymbol symbol, ISymbol containingContextSymbol, Compilation compilation, CancellationToken cancellationToken, SymbolVisibilityGroup defaultRequiredVisibility = SymbolVisibilityGroup.Public) { var allowedVisibilities = options.GetSymbolVisibilityGroupOption(rule, containingContextSymbol, compilation, defaultRequiredVisibility, cancellationToken); return allowedVisibilities == SymbolVisibilityGroup.All || allowedVisibilities.Contains(symbol.GetResultantVisibility()); } /// <summary> /// Returns true if the given symbol has required symbol modifiers based on options: /// 1. If user has explicitly configured candidate <see cref="SymbolModifiers"/> in editor config options and /// given symbol has all the required modifiers. /// 2. Otherwise, if user has not configured modifiers. /// </summary> public static bool MatchesConfiguredModifiers( this AnalyzerOptions options, DiagnosticDescriptor rule, ISymbol symbol, Compilation compilation, CancellationToken cancellationToken, SymbolModifiers defaultRequiredModifiers = SymbolModifiers.None) { var requiredModifiers = options.GetRequiredModifiersOption(rule, symbol, compilation, defaultRequiredModifiers, cancellationToken); return symbol.GetSymbolModifiers().Contains(requiredModifiers); } #pragma warning disable CA1801 // Review unused parameters - 'compilation' is used conditionally. private static ICategorizedAnalyzerConfigOptions GetOrComputeCategorizedAnalyzerConfigOptions( this AnalyzerOptions options, Compilation compilation, CancellationToken cancellationToken) #pragma warning restore CA1801 // Review unused parameters { // TryGetValue upfront to avoid allocating createValueCallback if the entry already exists.
<<<<<<< public const string SystemTextEncoding = "System.Text.Encoding"; ======= public const string SystemNetServicePointManager = "System.Net.ServicePointManager"; public const string SystemRandom = "System.Random"; public const string SystemSecurityAuthenticationSslProtocols = "System.Security.Authentication.SslProtocols"; >>>>>>> public const string SystemNetServicePointManager = "System.Net.ServicePointManager"; public const string SystemRandom = "System.Random"; public const string SystemSecurityAuthenticationSslProtocols = "System.Security.Authentication.SslProtocols"; public const string SystemTextEncoding = "System.Text.Encoding";
<<<<<<< public const string SystemCollectionsConcurrentConcurrentDictionary2 = "System.Collections.Concurrent.ConcurrentDictionary`2"; public const string SystemCollectionsGenericDictionary2 = "System.Collections.Generic.Dictionary`2"; public const string SystemCollectionsGenericHashSet1 = "System.Collections.Generic.HashSet`1"; ======= public const string SystemCollectionsConcurrentConcurrentBag1 = "System.Collections.Concurrent.ConcurrentBag`1"; public const string SystemCollectionsConcurrentConcurrentDictionary2 = "System.Collections.Concurrent.ConcurrentDictionary`2"; public const string SystemCollectionsConcurrentConcurrentQueue1 = "System.Collections.Concurrent.ConcurrentQueue`1"; public const string SystemCollectionsConcurrentConcurrentStack1 = "System.Collections.Concurrent.ConcurrentStack`1"; >>>>>>> public const string SystemCollectionsConcurrentConcurrentBag1 = "System.Collections.Concurrent.ConcurrentBag`1"; public const string SystemCollectionsConcurrentConcurrentDictionary2 = "System.Collections.Concurrent.ConcurrentDictionary`2"; public const string SystemCollectionsConcurrentConcurrentQueue1 = "System.Collections.Concurrent.ConcurrentQueue`1"; public const string SystemCollectionsConcurrentConcurrentStack1 = "System.Collections.Concurrent.ConcurrentStack`1"; public const string SystemCollectionsGenericDictionary2 = "System.Collections.Generic.Dictionary`2"; public const string SystemCollectionsGenericHashSet1 = "System.Collections.Generic.HashSet`1";
<<<<<<< public static INamedTypeSymbol XmlDocument(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.XmlDocument"); } public static INamedTypeSymbol XPathDocument(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.XPath.XPathDocument"); } public static INamedTypeSymbol XmlSchema(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.Schema.XmlSchema"); } public static INamedTypeSymbol DataSet(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Data.DataSet"); } public static INamedTypeSymbol XmlSerializer(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.Serialization.XmlSerializer"); } public static INamedTypeSymbol DataTable(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Data.DataTable"); } public static INamedTypeSymbol XmlNode(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.XmlNode"); } public static INamedTypeSymbol DataViewManager(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Data.DataViewManager"); } public static INamedTypeSymbol XmlTextReader(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.XmlTextReader"); } public static INamedTypeSymbol XmlReader(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.XmlReader"); } public static INamedTypeSymbol DtdProcessing(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.DtdProcessing"); } public static INamedTypeSymbol XmlReaderSettings(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.XmlReaderSettings"); } public static INamedTypeSymbol XslCompiledTransform(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.Xsl.XslCompiledTransform"); } public static INamedTypeSymbol XmlResolver(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.XmlResolver"); } public static INamedTypeSymbol XmlSecureResolver(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.XmlSecureResolver"); } public static INamedTypeSymbol XsltSettings(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.Xsl.XsltSettings"); } ======= public static INamedTypeSymbol DES(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Security.Cryptography.DES"); } public static INamedTypeSymbol DSA(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Security.Cryptography.DSA"); } public static INamedTypeSymbol DSASignatureFormatter(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Security.Cryptography.DSASignatureFormatter"); } public static INamedTypeSymbol HMACMD5(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Security.Cryptography.HMACMD5"); } public static INamedTypeSymbol RC2(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Security.Cryptography.RC2"); } public static INamedTypeSymbol Rijndael(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Security.Cryptography.Rijndael"); } public static INamedTypeSymbol TripleDES(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Security.Cryptography.TripleDES"); } public static INamedTypeSymbol RIPEMD160(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Security.Cryptography.RIPEMD160"); } public static INamedTypeSymbol HMACRIPEMD160(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Security.Cryptography.HMACRIPEMD160"); } >>>>>>> public static INamedTypeSymbol XmlDocument(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.XmlDocument"); } public static INamedTypeSymbol XPathDocument(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.XPath.XPathDocument"); } public static INamedTypeSymbol XmlSchema(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.Schema.XmlSchema"); } public static INamedTypeSymbol DataSet(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Data.DataSet"); } public static INamedTypeSymbol XmlSerializer(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.Serialization.XmlSerializer"); } public static INamedTypeSymbol DataTable(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Data.DataTable"); } public static INamedTypeSymbol XmlNode(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.XmlNode"); } public static INamedTypeSymbol DataViewManager(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Data.DataViewManager"); } public static INamedTypeSymbol XmlTextReader(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.XmlTextReader"); } public static INamedTypeSymbol XmlReader(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.XmlReader"); } public static INamedTypeSymbol DtdProcessing(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.DtdProcessing"); } public static INamedTypeSymbol XmlReaderSettings(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.XmlReaderSettings"); } public static INamedTypeSymbol XslCompiledTransform(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.Xsl.XslCompiledTransform"); } public static INamedTypeSymbol XmlResolver(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.XmlResolver"); } public static INamedTypeSymbol XmlSecureResolver(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.XmlSecureResolver"); } public static INamedTypeSymbol XsltSettings(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Xml.Xsl.XsltSettings"); } public static INamedTypeSymbol DES(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Security.Cryptography.DES"); } public static INamedTypeSymbol DSA(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Security.Cryptography.DSA"); } public static INamedTypeSymbol DSASignatureFormatter(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Security.Cryptography.DSASignatureFormatter"); } public static INamedTypeSymbol HMACMD5(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Security.Cryptography.HMACMD5"); } public static INamedTypeSymbol RC2(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Security.Cryptography.RC2"); } public static INamedTypeSymbol Rijndael(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Security.Cryptography.Rijndael"); } public static INamedTypeSymbol TripleDES(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Security.Cryptography.TripleDES"); } public static INamedTypeSymbol RIPEMD160(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Security.Cryptography.RIPEMD160"); } public static INamedTypeSymbol HMACRIPEMD160(Compilation compilation) { return compilation.GetTypeByMetadataName("System.Security.Cryptography.HMACRIPEMD160"); }
<<<<<<< NetworkManager.transport.ClientDisconnect(); ======= if (NetworkManager.singleton.transport.ClientConnected()) { NetworkManager.singleton.transport.ClientDisconnect(); } >>>>>>> NetworkManager.singleton.transport.ClientDisconnect();
<<<<<<< using System.Collections.Generic; using Mono.Cecil; ======= using System; using Mono.CecilX; >>>>>>> using System; using Mono.Cecil; <<<<<<< public TypeReference GetGenericFromBaseClass(TypeDefinition td, int genericArgument, TypeReference baseType) { if (GetGenericBaseType(td, baseType, out GenericInstanceType parent)) { TypeReference arg = parent.GenericArguments[genericArgument]; if (arg.IsGenericParameter) { return FindParameterInStack(td, genericArgument); } else { return Weaver.CurrentAssembly.MainModule.ImportReference(arg); } } return null; } TypeReference FindParameterInStack(TypeDefinition td, int genericArgument) { while (stack.Count > 0) ======= TypeReference[] resolvedArguments = new TypeReference[0]; if (tr is GenericInstanceType genericInstance) >>>>>>> var resolvedArguments = new TypeReference[0]; if (tr is GenericInstanceType genericInstance)
<<<<<<< using Mono.Cecil; ======= using System.Collections.Generic; using Mono.CecilX; >>>>>>> using System.Collections.Generic; using Mono.Cecil;
<<<<<<< // serialize var writer = new NetworkWriter(); message.Serialize(writer); byte[] writerData = writer.ToArray(); ======= byte[] arr = MessagePacker.Pack(message); >>>>>>> byte[] arr = MessagePacker.Pack(message); <<<<<<< var fresh = new CommandMessage(); fresh.Deserialize(new NetworkReader(writerData)); ======= CommandMessage fresh = MessagePacker.Unpack<CommandMessage>(arr); >>>>>>> CommandMessage fresh = MessagePacker.Unpack<CommandMessage>(arr); <<<<<<< // serialize var writer = new NetworkWriter(); message.Serialize(writer); byte[] writerData = writer.ToArray(); // deserialize the same data - do we get the same result? var fresh = new T(); fresh.Deserialize(new NetworkReader(writerData)); Assert.That(fresh, Is.EqualTo(message)); ======= // try setting value with constructor ConnectMessage message = new ConnectMessage(); byte[] arr = MessagePacker.Pack(message); Assert.DoesNotThrow(() => { MessagePacker.Unpack<ConnectMessage>(arr); }); >>>>>>> // serialize byte[] arr = MessagePacker.Pack(message); T fresh = MessagePacker.Unpack<T>(arr); Assert.That(fresh, Is.EqualTo(message)); <<<<<<< TestSerializeDeserialize(new DisconnectMessage()); ======= // try setting value with constructor DisconnectMessage message = new DisconnectMessage(); byte[] arr = MessagePacker.Pack(message); Assert.DoesNotThrow(() => { MessagePacker.Unpack<DisconnectMessage>(arr); }); >>>>>>> TestSerializeDeserialize(new DisconnectMessage()); <<<<<<< TestSerializeDeserialize(new ErrorMessage(42)); ======= // try setting value with constructor ErrorMessage message = new ErrorMessage(42); byte[] arr = MessagePacker.Pack(message); ErrorMessage fresh = MessagePacker.Unpack<ErrorMessage>(arr); Assert.That(fresh.value, Is.EqualTo(message.value)); >>>>>>> TestSerializeDeserialize(new ErrorMessage(42)); <<<<<<< TestSerializeDeserialize(new NetworkPingMessage(DateTime.Now.ToOADate())); ======= // try setting value with constructor NetworkPingMessage message = new NetworkPingMessage(DateTime.Now.ToOADate()); byte[] arr = MessagePacker.Pack(message); NetworkPingMessage fresh = MessagePacker.Unpack<NetworkPingMessage>(arr); Assert.That(fresh.clientTime, Is.EqualTo(message.clientTime)); >>>>>>> TestSerializeDeserialize(new NetworkPingMessage(DateTime.Now.ToOADate())); <<<<<<< }); ======= }; byte[] arr = MessagePacker.Pack(message); NetworkPongMessage fresh = MessagePacker.Unpack<NetworkPongMessage>(arr); Assert.That(fresh.clientTime, Is.EqualTo(message.clientTime)); Assert.That(fresh.serverTime, Is.EqualTo(message.clientTime)); >>>>>>> }); <<<<<<< TestSerializeDeserialize(new NotReadyMessage()); ======= // try setting value with constructor NotReadyMessage message = new NotReadyMessage(); byte[] arr = MessagePacker.Pack(message); Assert.DoesNotThrow(() => { NotReadyMessage fresh = MessagePacker.Unpack<NotReadyMessage>(arr); }); >>>>>>> TestSerializeDeserialize(new NotReadyMessage()); <<<<<<< }); ======= }; byte[] arr = MessagePacker.Pack(message); ObjectDestroyMessage fresh = MessagePacker.Unpack<ObjectDestroyMessage>(arr); Assert.That(fresh.netId, Is.EqualTo(message.netId)); >>>>>>> }); <<<<<<< }); ======= }; byte[] arr = MessagePacker.Pack(message); ObjectHideMessage fresh = MessagePacker.Unpack<ObjectHideMessage>(arr); Assert.That(fresh.netId, Is.EqualTo(message.netId)); >>>>>>> }); <<<<<<< TestSerializeDeserialize(new ObjectSpawnFinishedMessage()); ======= // try setting value with constructor ObjectSpawnFinishedMessage message = new ObjectSpawnFinishedMessage(); byte[] arr = MessagePacker.Pack(message); Assert.DoesNotThrow(() => { ObjectSpawnFinishedMessage fresh = MessagePacker.Unpack<ObjectSpawnFinishedMessage>(arr); }); >>>>>>> TestSerializeDeserialize(new ObjectSpawnFinishedMessage()); <<<<<<< TestSerializeDeserialize(new ObjectSpawnStartedMessage()); ======= ObjectSpawnStartedMessage message = new ObjectSpawnStartedMessage(); byte[] arr = MessagePacker.Pack(message); Assert.DoesNotThrow(() => { ObjectSpawnStartedMessage fresh = MessagePacker.Unpack<ObjectSpawnStartedMessage>(arr); }); >>>>>>> TestSerializeDeserialize(new ObjectSpawnStartedMessage()); <<<<<<< TestSerializeDeserialize(new ReadyMessage()); } [Test] public void AddPlayerMessageTest() { TestSerializeDeserialize(new AddPlayerMessage()); ======= // try setting value with constructor ReadyMessage message = new ReadyMessage(); byte[] arr = MessagePacker.Pack(message); Assert.DoesNotThrow(() => { ReadyMessage fresh = MessagePacker.Unpack<ReadyMessage>(arr); }); >>>>>>> TestSerializeDeserialize(new ReadyMessage()); } [Test] public void AddPlayerMessageTest() { TestSerializeDeserialize(new AddPlayerMessage()); <<<<<<< TestSerializeDeserialize(new RemovePlayerMessage()); ======= // try setting value with constructor RemovePlayerMessage message = new RemovePlayerMessage(); byte[] arr = MessagePacker.Pack(message); Assert.DoesNotThrow(() => { RemovePlayerMessage fresh = MessagePacker.Unpack<RemovePlayerMessage>(arr); }); >>>>>>> TestSerializeDeserialize(new RemovePlayerMessage()); <<<<<<< // serialize var writer = new NetworkWriter(); message.Serialize(writer); byte[] writerData = writer.ToArray(); // deserialize the same data - do we get the same result? var fresh = new RpcMessage(); fresh.Deserialize(new NetworkReader(writerData)); ======= byte[] arr = MessagePacker.Pack(message); RpcMessage fresh = MessagePacker.Unpack<RpcMessage>(arr); >>>>>>> byte[] arr = MessagePacker.Pack(message); RpcMessage fresh = MessagePacker.Unpack<RpcMessage>(arr); <<<<<<< UnityEngine.Debug.Log($"sceneId:{message.sceneId} | assetId:{message.assetId}"); // serialize var writer = new NetworkWriter(); message.Serialize(writer); byte[] writerData = writer.ToArray(); // deserialize the same data - do we get the same result? var fresh = new SpawnMessage(); fresh.Deserialize(new NetworkReader(writerData)); ======= byte[] arr = MessagePacker.Pack(message); SpawnMessage fresh = MessagePacker.Unpack<SpawnMessage>(arr); >>>>>>> byte[] arr = MessagePacker.Pack(message); SpawnMessage fresh = MessagePacker.Unpack<SpawnMessage>(arr); <<<<<<< // serialize var writer = new NetworkWriter(); message.Serialize(writer); byte[] writerData = writer.ToArray(); // deserialize the same data - do we get the same result? var fresh = new SyncEventMessage(); fresh.Deserialize(new NetworkReader(writerData)); ======= >>>>>>> <<<<<<< // serialize var writer = new NetworkWriter(); message.Serialize(writer); byte[] writerData = writer.ToArray(); // deserialize the same data - do we get the same result? var fresh = new UpdateVarsMessage(); fresh.Deserialize(new NetworkReader(writerData)); ======= byte[] arr = MessagePacker.Pack(message); UpdateVarsMessage fresh = MessagePacker.Unpack<UpdateVarsMessage>(arr); >>>>>>> byte[] arr = MessagePacker.Pack(message); UpdateVarsMessage fresh = MessagePacker.Unpack<UpdateVarsMessage>(arr);
<<<<<<< ======= internal static NetworkMessageDelegate MessageHandler<T, C>(Action<C, T> handler, bool requireAuthenication) where T : IMessageBase, new() where C : NetworkConnection => (conn, reader, channelId) => { // protect against DOS attacks if attackers try to send invalid // data packets to crash the server/client. there are a thousand // ways to cause an exception in data handling: // - invalid headers // - invalid message ids // - invalid data causing exceptions // - negative ReadBytesAndSize prefixes // - invalid utf8 strings // - etc. // // let's catch them all and then disconnect that connection to avoid // further attacks. T message = default; try { if (requireAuthenication && !conn.isAuthenticated) { // message requires authentication, but the connection was not authenticated logger.LogWarning($"Closing connection: {conn}. Received message {typeof(T)} that required authentication, but the user has not authenticated yet"); conn.Disconnect(); return; } // if it is a value type, just use defult(T) // otherwise allocate a new instance message = default(T) != null ? default(T) : new T(); message.Deserialize(reader); } catch (Exception exception) { logger.LogError("Closed connection: " + conn + ". This can happen if the other side accidentally (or an attacker intentionally) sent invalid data. Reason: " + exception); conn.Disconnect(); return; } finally { // TODO: Figure out the correct channel NetworkDiagnostics.OnReceive(message, channelId, reader.Length); } handler((C)conn, message); }; >>>>>>>
<<<<<<< bool SendToObservers<T>(NetworkIdentity identity, T msg) where T : IMessageBase ======= static bool SendToObservers<T>(NetworkIdentity identity, T msg, int channelId = Channels.DefaultReliable) where T : IMessageBase >>>>>>> bool SendToObservers<T>(NetworkIdentity identity, T msg, int channelId = Channels.DefaultReliable) where T : IMessageBase <<<<<<< public void SendToClientOfPlayer<T>(NetworkIdentity identity, T msg) where T : IMessageBase ======= public static void SendToClientOfPlayer<T>(NetworkIdentity identity, T msg, int channelId = Channels.DefaultReliable) where T : IMessageBase >>>>>>> public void SendToClientOfPlayer<T>(NetworkIdentity identity, T msg, int channelId = Channels.DefaultReliable) where T : IMessageBase <<<<<<< bool GetNetworkIdentity(GameObject go, out NetworkIdentity identity) ======= internal static bool GetNetworkIdentity(GameObject go, out NetworkIdentity identity) >>>>>>> internal bool GetNetworkIdentity(GameObject go, out NetworkIdentity identity) <<<<<<< bool ValidateSceneObject(NetworkIdentity identity) ======= // Deprecated 01/15/2019 /// <summary> /// Obsolete: Use <see cref="NetworkIdentity.spawned"/> instead. /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use NetworkIdentity.spawned[netId] instead.")] public static GameObject FindLocalObject(uint netId) { if (NetworkIdentity.spawned.TryGetValue(netId, out NetworkIdentity identity)) { return identity.gameObject; } return null; } internal static bool ValidateSceneObject(NetworkIdentity identity) >>>>>>> internal bool ValidateSceneObject(NetworkIdentity identity)
<<<<<<< void SerializeAllTo<T>(T fromList, T toList) where T : ISyncObject ======= public static void SerializeAllTo<T>(T fromList, T toList) where T : SyncObject >>>>>>> public static void SerializeAllTo<T>(T fromList, T toList) where T : ISyncObject <<<<<<< void SerializeDeltaTo<T>(T fromList, T toList) where T : ISyncObject ======= public static void SerializeDeltaTo<T>(T fromList, T toList) where T : SyncObject >>>>>>> public static void SerializeDeltaTo<T>(T fromList, T toList) where T : ISyncObject
<<<<<<< var reader = new NetworkReader(buffer); if (MessagePacker.UnpackMessage(reader, out int msgType)) ======= NetworkReader networkReader = NetworkReaderPool.GetReader(buffer); if (MessagePacker.UnpackMessage(networkReader, out int msgType)) >>>>>>> var networkReader = NetworkReaderPool.GetReader(buffer); if (MessagePacker.UnpackMessage(networkReader, out int msgType))