System.Diagnostics.Debug.WriteLine(string)

Here are the examples of the csharp api System.Diagnostics.Debug.WriteLine(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

8294 Examples 7

19 Source : ItemPropertyFactory.cs
with MIT License
from 0xC0000054

internal IItemProperty TryCreate(in EndianBinaryReaderSegment reader, Box header)
        {
            IItemProperty property;

            if (header.Type == BoxTypes.ImageSpatialExtents)
            {
                property = new ImageSpatialExtentsBox(reader, header);
            }
            else if (header.Type == BoxTypes.PixelAspectRatio)
            {
                property = new PixelAspectRatioBox(reader, header);
            }
            else if (header.Type == BoxTypes.AV1Config)
            {
                property = new AV1ConfigBox(reader, header);
            }
            else if (header.Type == BoxTypes.AuxiliaryTypeProperty)
            {
                property = new AuxiliaryTypePropertyBox(reader, header);
            }
            else if (header.Type == BoxTypes.ColorInformation)
            {
                ColorInformationBox colorInformation = new ColorInformationBox(reader, header);

                if (colorInformation.ColorType == ColorInformationBoxTypes.IccProfile ||
                    colorInformation.ColorType == ColorInformationBoxTypes.RestrictedIccProfile)
                {
                    property = new IccProfileColorInformation(reader, colorInformation);
                }
                else if (colorInformation.ColorType == ColorInformationBoxTypes.Nclx)
                {
                    property = new NclxColorInformation(reader, colorInformation);
                }
                else
                {
                    // Ignore any unknown ColorInformationBox types.
                    Debug.WriteLine($"Unsupported ColorInformationBox type: { colorInformation.ColorType }.");
                    property = null;
                }
            }
            else if (header.Type == BoxTypes.PixelInformation)
            {
                property = new PixelInformationBox(reader, header);
            }
            else if (header.Type == BoxTypes.CleanAperture)
            {
                property = new CleanApertureBox(reader, header);
                this.transformPropertySeen = true;
            }
            else if (header.Type == BoxTypes.ImageMirror)
            {
                property = new ImageMirrorBox(reader, header);
                this.transformPropertySeen = true;
            }
            else if (header.Type == BoxTypes.ImageRotation)
            {
                property = new ImageRotateBox(reader, header);
                this.transformPropertySeen = true;
            }
            else if (header.Type == BoxTypes.AV1LayeredImageIndexing)
            {
                property = new AV1LayeredImageIndexingBox(reader, header);
            }
            else if (header.Type == BoxTypes.AV1OperatingPoint)
            {
                property = new AV1OperatingPointBox(reader, header);
            }
            else if (header.Type == BoxTypes.LayerSelector)
            {
                if (this.transformPropertySeen)
                {
                    ExceptionUtil.ThrowFormatException("The layer selector property must come before the transform properties.");
                }

                property = new LayerSelectorBox(reader, header);
            }
            else
            {
                Debug.WriteLine($"Unsupported property type: { header.Type }.");
                property = null;
            }

            return property;
        }

19 Source : ExifParser.cs
with MIT License
from 0xC0000054

private static List<ParserIFDEntry> ParseDirectories(EndianBinaryReader reader, uint firstIFDOffset)
        {
            List<ParserIFDEntry> items = new List<ParserIFDEntry>();

            bool foundExif = false;
            bool foundGps = false;
            bool foundInterop = false;

            Queue<MetadataOffset> ifdOffsets = new Queue<MetadataOffset>();
            ifdOffsets.Enqueue(new MetadataOffset(MetadataSection.Image, firstIFDOffset));

            while (ifdOffsets.Count > 0)
            {
                MetadataOffset metadataOffset = ifdOffsets.Dequeue();

                MetadataSection section = metadataOffset.Section;
                uint offset = metadataOffset.Offset;

                if (offset >= reader.Length)
                {
                    continue;
                }

                reader.Position = offset;

                ushort count = reader.ReadUInt16();
                if (count == 0)
                {
                    continue;
                }

                items.Capacity += count;

                for (int i = 0; i < count; i++)
                {
                    ParserIFDEntry entry = new ParserIFDEntry(reader, section);

                    switch (entry.Tag)
                    {
                        case TiffConstants.Tags.ExifIFD:
                            if (!foundExif)
                            {
                                foundExif = true;
                                ifdOffsets.Enqueue(new MetadataOffset(MetadataSection.Exif, entry.Offset));
                            }
                            break;
                        case TiffConstants.Tags.GpsIFD:
                            if (!foundGps)
                            {
                                foundGps = true;
                                ifdOffsets.Enqueue(new MetadataOffset(MetadataSection.Gps, entry.Offset));
                            }
                            break;
                        case TiffConstants.Tags.InteropIFD:
                            if (!foundInterop)
                            {
                                foundInterop = true;
                                ifdOffsets.Enqueue(new MetadataOffset(MetadataSection.Interop, entry.Offset));
                            }
                            break;
                        case TiffConstants.Tags.StripOffsets:
                        case TiffConstants.Tags.RowsPerStrip:
                        case TiffConstants.Tags.StripByteCounts:
                        case TiffConstants.Tags.SubIFDs:
                        case TiffConstants.Tags.ThumbnailOffset:
                        case TiffConstants.Tags.ThumbnailLength:
                            // Skip the thumbnail and/or preview images.
                            // The StripOffsets and StripByteCounts tags are used to store a preview image in some formats.
                            // The SubIFDs tag is used to store thumbnails in TIFF and for storing other data in some camera formats.
                            //
                            // Note that some cameras will also store a thumbnail as part of their private data in the EXIF MakerNote tag.
                            // The EXIF MakerNote tag is treated as an opaque blob, so those thumbnails will be preserved.
                            break;
                        default:
                            items.Add(entry);
                            break;
                    }

                    System.Diagnostics.Debug.WriteLine(entry.ToString());
                }
            }

            return items;
        }

19 Source : ExtensionMethods.cs
with MIT License
from 1iveowl

internal static IObservable<T> FinallyAsync<T>(this IObservable<T> source, Func<Task> finalAsync)
        {
            return source
                .Materialize()
                .SelectMany(async n =>
                {
                    switch (n.Kind)
                    {
                        case NotificationKind.OnCompleted:
                            Debug.WriteLine("------ OnCompleted -----");
                            await finalAsync();
                            return n;
                        case NotificationKind.OnError:
                            Debug.WriteLine("------ OnError -----");
                            await finalAsync();
                            return n;
                        case NotificationKind.OnNext:
                            return n;
                        default:throw new NotImplementedException();
                    }
                })
                .Dematerialize();
        }

19 Source : MQTTService.cs
with MIT License
from 1iveowl

public (IObservable<IMQTTMessage> observableMessage, IMQTTClient client)
            CreateObservableMQTTClient(
                IClientOptions options,
                IWillMessage willMessage = null,
                params ITopicFilter[] topicFilters)
        {
            ClientOptions = options;
            WillMessage = willMessage;

             _wrappedClient = new MQTTClient(this, topicFilters);

            var observable = Observable.Create<IMQTTMessage>(
                    obs =>
                    {
                        var disposableConnect = _wrappedClient.ObservableConnect
                            .Subscribe(_ =>
                            {

                            },
                            obs.OnError,
                            obs.OnCompleted);

                        var disposableMessage = _wrappedClient.ObservableMessage
                            .Subscribe(
                                obs.OnNext,
                                obs.OnError,
                                obs.OnCompleted);

                        var disposableDisconnect = _wrappedClient.ObservableDisconnect
                            .Where(disconnect => disconnect == true)
                            .Select(x => Observable.FromAsync(() => _wrappedClient.DisconnectAsync()).Timeout(TimeSpan.FromSeconds(5)))
                            .Concat()
                            .Subscribe(d =>
                                {
                                    Debug.WriteLine("Disconnected");
                                    obs.OnCompleted();
                                },
                                obs.OnError,
                                obs.OnCompleted);

                        return new CompositeDisposable(
                            disposableMessage,
                            disposableConnect,
                            disposableDisconnect);
                    })
                .FinallyAsync(async () => { await _wrappedClient?.DisconnectAsync(); })
                .Publish().RefCount();

            return (observable, _wrappedClient);
        }

19 Source : TcpClientEx.cs
with MIT License
from 1iveowl

private static IObservable<byte[]> CreateByteStreamObservable2(Stream stream, TcpClient tcpClient, CancellationToken ct)
        {
            var observableBytes = Observable.Create<byte[]>(obs =>
            {
                while (!ct.IsCancellationRequested)
                {
                    if (ct.IsCancellationRequested || !tcpClient.Connected)
                    {
                        obs.OnNext(Enumerable.Empty<byte>().ToArray());
                    }

                    var oneByteArray = new byte[1];

                    try
                    {
                        if (stream == null)
                        {
                            throw new Exception("Read stream cannot be null.");
                        }

                        if (!stream.CanRead)
                        {
                            throw new Exception("Stream connection have been closed.");
                        }

                        var bytesRead = stream.ReadByte();

;                        //var bytesRead = await stream.ReadAsync(oneByteArray, 0, 1, ct).ConfigureAwait(false);

                        if (bytesRead < oneByteArray.Length)
                        {
                            throw new Exception("Stream connection aborted unexpectedly. Check connection and socket security version/TLS version).");
                        }
                    }
                    catch (ObjectDisposedException)
                    {
                        Debug.WriteLine("Ignoring Object Disposed Exception - This is an expected exception.");
                        obs.OnNext(Enumerable.Empty<byte>().ToArray());
                    }
                    catch (IOException)
                    {
                        obs.OnNext(Enumerable.Empty<byte>().ToArray());
                    }

                    obs.OnNext(oneByteArray);
                }

                obs.OnCompleted();

                return Disposable.Empty;
            });

            return observableBytes.SubscribeOn(Scheduler.Default);
        }

19 Source : HttpSender.cs
with MIT License
from 1iveowl

private byte[] ComposeResponse(IHttpRequest request, IHttpResponse response)
        {
            var stringBuilder = new StringBuilder();

            stringBuilder.Append(
                $"HTTP/{request.MajorVersion}.{request.MinorVersion} {(int)response.StatusCode} {response.ResponseReason}\r\n");

            if (response.Headers != null)
            {
                if (response.Headers.Any())
                {
                    foreach (var header in response.Headers)
                    {
                        stringBuilder.Append($"{header.Key}: {header.Value}\r\n");
                    }
                }
            }

            if (response.Body?.Length > 0)
            {
                stringBuilder.Append($"Content-Length: {response?.Body?.Length}");
            }

            stringBuilder.Append("\r\n\r\n");

            var datagram = Encoding.UTF8.GetBytes(stringBuilder.ToString());


            if (response.Body?.Length > 0)
            {
                datagram = datagram.Concat(response?.Body?.ToArray()).ToArray();
            }

            Debug.WriteLine(Encoding.UTF8.GetString(datagram, 0, datagram.Length));
            return datagram;
        }

19 Source : CosmosClientStreamWrapper.cs
with MIT License
from 1iveowl

internal async Task<T> Read<T>(string id, CancellationToken ct)
        {
            ResponseMessage response;

            try
            {
                response = await _container.ReadItemStreamAsync(id, _parreplacedionKey, cancellationToken:ct);

            }
            catch (Exception ex)
            {
                Debug.WriteLine($"{ex}");
                throw new CosmosClientException($"Unable to read: {id} to Stream", ex);
            }

            try
            {
                if (response.IsSuccessStatusCode)
                {
                    await using var cosmosItem = new CosmosItem<T>();

                    var item = await cosmosItem.GereplacedemFromStream(response.Content, ct);

                    return item;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"{ex}");
                throw new CosmosClientException($"Unable deserialize doreplacedent with '{id}' from Stream.", ex);
            }

            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                throw new DataException($"Doreplacedent with id '{id}' not found");
            }

            throw new CosmosClientException($"Unable to read: {id} to Stream. Status code: {response.StatusCode.ToString()}");

        }

19 Source : TcpClientEx.cs
with MIT License
from 1iveowl

private static async Task<byte[]> ReadOneByteAtTheTimeAsync(Stream stream, CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                return Enumerable.Empty<byte>().ToArray();
            }

            var oneByteArray = new byte[1];

            try
            {
                if (stream == null)
                {
                    throw new Exception("Read stream cannot be null.");
                }

                if (!stream.CanRead)
                {
                    throw new Exception("Stream connection have been closed.");
                }

                var bytesRead = await stream.ReadAsync(oneByteArray, 0, 1, ct).ConfigureAwait(false);

                if (bytesRead < oneByteArray.Length)
                {
                    throw new Exception("Stream connection aborted unexpectedly. Check connection and socket security version/TLS version).");
                }
            }
            catch (ObjectDisposedException)
            {
                Debug.WriteLine("Ignoring Object Disposed Exception - This is an expected exception.");
                return Enumerable.Empty<byte>().ToArray();
            }
            catch (IOException)
            {
                return Enumerable.Empty<byte>().ToArray();
            }

            return oneByteArray;
        }

19 Source : TcpListenerEx.cs
with MIT License
from 1iveowl

private static async Task<TcpClient> WaitForNextRequestAsync(TcpListener tcpListener)
        {
            Debug.WriteLine("Ready for next Tcp Connection.");

            return await tcpListener.AcceptTcpClientAsync().ConfigureAwait(false);
        }

19 Source : FauxDeployCMAgent.cs
with GNU General Public License v3.0
from 1RedOne

public static void SendDiscovery(string CMServerName, string clientName, string domainName, string SiteCode,
            string CertPath, SecureString preplaced, SmsClientId clientId, ILog log, bool enumerateAndAddCustomDdr = false)
        {
            using (MessageCertificateX509Volatile certificate = new MessageCertificateX509Volatile(CertPath, preplaced))

            {
                //X509Certificate2 thisCert = new X509Certificate2(CertPath, preplaced);

                log.Info($"Got SMSID from registration of: {clientId}");

                // create base DDR Message
                ConfigMgrDataDiscoveryRecordMessage ddrMessage = new ConfigMgrDataDiscoveryRecordMessage
                {
                    // Add necessary discovery data
                    SmsId = clientId,
                    ADSiteName = "Default-First-Site-Name", //Changed from 'My-AD-SiteName
                    SiteCode = SiteCode,
                    DomainName = domainName,
                    NetBiosName = clientName
                };

                ddrMessage.Discover();
                // Add our certificate for message signing
                ddrMessage.AddCertificateToMessage(certificate, CertificatePurposes.Signing);
                ddrMessage.AddCertificateToMessage(certificate, CertificatePurposes.Encryption);
                ddrMessage.Settings.HostName = CMServerName;
                ddrMessage.Settings.Compression = MessageCompression.Zlib;
                ddrMessage.Settings.ReplyCompression = MessageCompression.Zlib;
                Debug.WriteLine("Sending [" + ddrMessage.DdrInstances.Count + "] instances of Discovery data to CM");
                if (enumerateAndAddCustomDdr)
                {
                    //see current value for the DDR message
                    var OSSetting = ddrMessage.DdrInstances.OfType<InventoryInstance>().Where(m => m.Clreplaced == "CCM_DiscoveryData");

                    ////retrieve actual setting
                    string osCaption = (from x in new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem").Get().Cast<ManagementObject>()
                                        select x.GetPropertyValue("Caption")).FirstOrDefault().ToString();

                    XmlDoreplacedent xmlDoc = new XmlDoreplacedent();

                    ////retrieve reported value
                    xmlDoc.LoadXml(ddrMessage.DdrInstances.OfType<InventoryInstance>().FirstOrDefault(m => m.Clreplaced == "CCM_DiscoveryData")?.InstanceDataXml.ToString());

                    ////Set OS to correct setting
                    xmlDoc.SelectSingleNode("/CCM_DiscoveryData/PlatformID").InnerText = "Microsoft Windows NT Server 10.0";

                    ////Remove the instance
                    ddrMessage.DdrInstances.Remove(ddrMessage.DdrInstances.OfType<InventoryInstance>().FirstOrDefault(m => m.Clreplaced == "CCM_DiscoveryData"));

                    CMFauxStatusViewClreplacedesFixedOSRecord FixedOSRecord = new CMFauxStatusViewClreplacedesFixedOSRecord
                    {
                        PlatformId = osCaption
                    };
                    InventoryInstance instance = new InventoryInstance(FixedOSRecord);

                    ////Add new instance
                    ddrMessage.DdrInstances.Add(instance);
                }

                ddrMessage.SendMessage(Sender);

                ConfigMgrHardwareInventoryMessage hinvMessage = new ConfigMgrHardwareInventoryMessage();
                hinvMessage.Settings.HostName = CMServerName;
                hinvMessage.SmsId = clientId;
                hinvMessage.Settings.Compression = MessageCompression.Zlib;
                hinvMessage.Settings.ReplyCompression = MessageCompression.Zlib;
                //hinvMessage.Settings.Security.EncryptMessage = true;
                hinvMessage.Discover();

                var Clreplacedes = CMFauxStatusViewClreplacedes.GetWMIClreplacedes();
                foreach (string Clreplaced in Clreplacedes)
                {
                    try { hinvMessage.AddInstancesToInventory(WmiClreplacedToInventoryReportInstance.WmiClreplacedToInventoryInstances(@"root\cimv2", Clreplaced)); }
                    catch { log.Info($"!!!Adding clreplaced : [{Clreplaced}] :( not found on this system"); }
                }

                var SMSClreplacedes = new List<string> { "SMS_Processor", "CCM_System", "SMS_LogicalDisk" };
                foreach (string Clreplaced in SMSClreplacedes)
                {
                    log.Info($"---Adding clreplaced : [{Clreplaced}]");
                    try { hinvMessage.AddInstancesToInventory(WmiClreplacedToInventoryReportInstance.WmiClreplacedToInventoryInstances(@"root\cimv2\sms", Clreplaced)); }
                    catch { log.Info($"!!!Adding clreplaced : [{Clreplaced}] :( not found on this system"); }
                }

                hinvMessage.AddCertificateToMessage(certificate, CertificatePurposes.Signing | CertificatePurposes.Encryption);
                hinvMessage.Validate(Sender);
                hinvMessage.SendMessage(Sender);
            };
        }

19 Source : ObjectPool.cs
with MIT License
from 2881099

internal static void WriteLine(string text, ConsoleColor backgroundColor)
        {
            try
            {
                var bgcolor = Console.BackgroundColor;
                var forecolor = Console.ForegroundColor;
                Console.BackgroundColor = backgroundColor;

                switch (backgroundColor)
                {
                    case ConsoleColor.DarkYellow:
                        Console.ForegroundColor = ConsoleColor.White;
                        break;
                    case ConsoleColor.DarkGreen:
                        Console.ForegroundColor = ConsoleColor.White;
                        break;
                }
                Console.Write(text);
                Console.BackgroundColor = bgcolor;
                Console.ForegroundColor = forecolor;
                Console.WriteLine();
            }
            catch
            {
                try
                {
                    System.Diagnostics.Debug.WriteLine(text);
                }
                catch { }
            }
        }

19 Source : WaveFormat.cs
with MIT License
from 3wz

private void ReadWaveFormat(BinaryReader br, int formatChunkLength)
        {
            if (formatChunkLength < 16)
                throw new ApplicationException("Invalid WaveFormat Structure");
            this.waveFormatTag = (WaveFormatEncoding)br.ReadUInt16();
            this.channels = br.ReadInt16();
            this.sampleRate = br.ReadInt32();
            this.averageBytesPerSecond = br.ReadInt32();
            this.blockAlign = br.ReadInt16();
            this.bitsPerSample = br.ReadInt16();
            if (formatChunkLength > 16)
            {
                this.extraSize = br.ReadInt16();
                if (this.extraSize != formatChunkLength - 18)
                {
                    Debug.WriteLine("Format chunk mismatch");
                    this.extraSize = (short)(formatChunkLength - 18);
                }
            }
        }

19 Source : SettingsManager.cs
with MIT License
from a1xd

private DriverConfig InitActiveAndGetUserConfig()
        {
            var path = Constants.DefaultSettingsFileName;
            if (File.Exists(path))
            {
                try
                {
                    var (cfg, err) = DriverConfig.Convert(File.ReadAllText(path));

                    if (err == null)
                    {
                        if (GuiSettings.AutoWriteToDriverOnStartup)
                        {
                            if (!TryActivate(cfg, out string _))
                            {
                                throw new Exception("deserialization succeeded but TryActivate failed");
                            }
                        }
                        else
                        {
                            ActiveConfig = DriverConfig.GetActive();
                        }

                        return cfg;
                    }
                }
                catch (JsonException e)
                {
                    System.Diagnostics.Debug.WriteLine($"bad settings: {e}");
                }
            }

            ActiveConfig = DriverConfig.GetActive();
            File.WriteAllText(path, ActiveConfig.ToJSON());
            return ActiveConfig;
        }

19 Source : VersionControlLogReader.cs
with MIT License
from aabiryukov

public override string ReadLine()
        {
            const int ChangesetTimeMilliseconds = 3000;

            if (m_vcs == null)
                Connect();

            if (m_latestChangesetId == 0)
            {
                // First run. Searching latest changeset
                var latestChangeset = GetLatestChangeset();
                if (latestChangeset == null)
                    return null; // No any chanesets found!

                foreach (var line in m_changesetConverter.GetLogLines(latestChangeset))
                {
                    m_latestChanges.Enqueue(line);
                }

                // How mutch a wait before get next line
                m_waitMilliseconds = m_latestChanges.Count > 0 ? ChangesetTimeMilliseconds / m_latestChanges.Count : 0;

                m_latestChangesetId = latestChangeset.ChangesetId;
            }
            else
            {
               if (m_latestChanges.Count == 0)
               {
                   // Getting new changes after latest previous changeset Id
                   var foundChanges = FindLatestChanges(m_latestChangesetId);
                   if (foundChanges != null)
                   {
                       foreach (var changeset in foundChanges)
                       {
                           foreach (var line in m_changesetConverter.GetLogLines(changeset))
                           {
                               m_latestChanges.Enqueue(line);
                           }

                           m_latestChangesetId = changeset.ChangesetId;
                       }
                   }

                   // How mutch a wait before get next line
                   m_waitMilliseconds = m_latestChanges.Count > 0 ? ChangesetTimeMilliseconds / m_latestChanges.Count : 0;
               }
            }

            if (m_latestChanges.Count == 0)
                return null;

            // Simulate changes time to avoid super fast
            var sleepTime = m_waitMilliseconds - (Environment.TickCount - m_lastReadLineTicks);
            if (sleepTime > 0 && sleepTime <= m_waitMilliseconds)
            {
                System.Diagnostics.Debug.WriteLine("WAIT: " + sleepTime);
                System.Threading.Thread.Sleep(sleepTime);
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("WAIT: none");
            }
            m_lastReadLineTicks = Environment.TickCount;

            return m_latestChanges.Dequeue();
        }

19 Source : TfsVisualHistoryVSPackage.cs
with MIT License
from aabiryukov

protected override void Initialize()
        {
            Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            ViewSourceControlHistoryCommand.Initialize(this);

            base.Initialize();
        }

19 Source : DocumentLineTree.cs
with MIT License
from Abdesol

public void RebuildTree(List<DoreplacedentLine> doreplacedentLines)
		{
			LineNode[] nodes = new LineNode[doreplacedentLines.Count];
			for (int i = 0; i < doreplacedentLines.Count; i++) {
				DoreplacedentLine ls = doreplacedentLines[i];
				LineNode node = ls.InitLineNode();
				nodes[i] = node;
			}
			Debug.replacedert(nodes.Length > 0);
			// now build the corresponding balanced tree
			int height = GetTreeHeight(nodes.Length);
			Debug.WriteLine("DoreplacedentLineTree will have height: " + height);
			root = BuildTree(nodes, 0, nodes.Length, height);
			root.color = BLACK;
#if DEBUG
			CheckProperties();
#endif
		}

19 Source : TextAnchorTree.cs
with MIT License
from Abdesol

[Conditional("DEBUG")]
		static void Log(string text)
		{
			Debug.WriteLine("TextAnchorTree: " + text);
		}

19 Source : Caret.cs
with MIT License
from Abdesol

void ValidateVisualColumn()
		{
			if (!visualColumnValid) {
				TextDoreplacedent doreplacedent = textArea.Doreplacedent;
				if (doreplacedent != null) {
					Debug.WriteLine("Explicit validation of caret column");
					var doreplacedentLine = doreplacedent.GetLineByNumber(position.Line);
					RevalidateVisualColumn(textView.GetOrConstructVisualLine(doreplacedentLine));
				}
			}
		}

19 Source : HighlightingColorizer.cs
with MIT License
from Abdesol

void OnHighlightStateChanged(int fromLineNumber, int toLineNumber)
		{
			if (lineNumberBeingColorized != 0) {
				// Ignore notifications for any line except the one we're interested in.
				// This improves the performance as Redraw() can take quite some time when called repeatedly
				// while scanning the doreplacedent (above the visible area) for highlighting changes.
				if (toLineNumber <= lineNumberBeingColorized) {
					return;
				}
			}

			// The user may have inserted "/*" into the current line, and so far only that line got redrawn.
			// So when the highlighting state is changed, we issue a redraw for the line immediately below.
			// If the highlighting state change applies to the lines below, too, the construction of each line
			// will invalidate the next line, and the construction preplaced will regenerate all lines.

			Debug.WriteLine(string.Format("OnHighlightStateChanged forces redraw of lines {0} to {1}", fromLineNumber, toLineNumber));

			// If the VisualLine construction is in progress, we have to avoid sending redraw commands for
			// anything above the line currently being constructed.
			// It takes some explanation to see why this cannot happen.
			// VisualLines always get constructed from top to bottom.
			// Each VisualLine construction calls into the highlighter and thus forces an update of the
			// highlighting state for all lines up to the one being constructed.

			// To guarantee that we don't redraw lines we just constructed, we need to show that when
			// a VisualLine is being reused, the highlighting state at that location is still up-to-date.

			// This isn't exactly trivial and the initial implementation was incorrect in the presence of external doreplacedent changes
			// (e.g. split view).

			// For the first line in the view, the TextView.VisualLineConstructionStarting event is used to check that the
			// highlighting state is up-to-date. If it isn't, this method will be executed, and it'll mark the first line
			// in the view as requiring a redraw. This is safely possible because that event occurs before any lines are reused.

			// Once we take care of the first visual line, we won't get in trouble with other lines due to the top-to-bottom
			// construction process.

			// We'll prove that: if line N is being reused, then the highlighting state is up-to-date until (end of) line N-1.

			// Start of induction: the first line in view is reused only if the highlighting state was up-to-date
			// until line N-1 (no change detected in VisualLineConstructionStarting event).

			// Induction step:
			// If another line N+1 is being reused, then either
			//     a) the previous line (the visual line containing doreplacedent line N) was newly constructed
			// or  b) the previous line was reused
			// In case a, the construction updated the highlighting state. This means the stack at end of line N is up-to-date.
			// In case b, the highlighting state at N-1 was up-to-date, and the text of line N was not changed.
			//   (if the text was changed, the line could not have been reused).
			// From this follows that the highlighting state at N is still up-to-date.

			// The above proof holds even in the presence of folding: folding only ever hides text in the middle of a visual line.
			// Our Colorize-override ensures that the highlighting state is always updated for the LastDoreplacedentLine,
			// so it will always invalidate the next visual line when a folded line is constructed
			// and the highlighting stack has changed.

			if (fromLineNumber == toLineNumber) {
				textView.Redraw(textView.Doreplacedent.GetLineByNumber(fromLineNumber));
			} else {
				// If there are multiple lines marked as changed; only the first one really matters
				// for the highlighting during rendering.
				// However this callback is also called outside of the rendering process, e.g. when a highlighter
				// decides to re-highlight some section based on external feedback (e.g. semantic highlighting).
				var fromLine = textView.Doreplacedent.GetLineByNumber(fromLineNumber);
				var toLine = textView.Doreplacedent.GetLineByNumber(toLineNumber);
				int startOffset = fromLine.Offset;
				textView.Redraw(startOffset, toLine.EndOffset - startOffset);
			}

			/*
			 * Meta-comment: "why does this have to be so complicated?"
			 * 
			 * The problem is that I want to re-highlight only on-demand and incrementally;
			 * and at the same time only repaint changed lines.
			 * So the highlighter and the VisualLine construction both have to run in a single preplaced.
			 * The highlighter must take care that it never touches already constructed visual lines;
			 * if it detects that something must be redrawn because the highlighting state changed,
			 * it must do so early enough in the construction process.
			 * But doing it too early means it doesn't have the information necessary to re-highlight and redraw only the desired parts.
			 */
		}

19 Source : HtmlClipboard.cs
with MIT License
from Abdesol

public static void SetHtml(DataObject dataObject, string htmlFragment)
		{
			if (dataObject == null)
				throw new ArgumentNullException("dataObject");
			if (htmlFragment == null)
				throw new ArgumentNullException("htmlFragment");

			string htmlStart = @"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">" + Environment.NewLine
				+ "<HTML>" + Environment.NewLine
				+ "<BODY>" + Environment.NewLine
				+ "<!--StartFragment-->" + Environment.NewLine;
			string htmlEnd = "<!--EndFragment-->" + Environment.NewLine + "</BODY>" + Environment.NewLine + "</HTML>" + Environment.NewLine;
			string dummyHeader = BuildHeader(0, 0, 0, 0);
			// the offsets are stored as UTF-8 bytes (see CF_HTML doreplacedentation)
			int startHTML = dummyHeader.Length;
			int startFragment = startHTML + htmlStart.Length;
			int endFragment = startFragment + Encoding.UTF8.GetByteCount(htmlFragment);
			int endHTML = endFragment + htmlEnd.Length;
			string cf_html = BuildHeader(startHTML, endHTML, startFragment, endFragment) + htmlStart + htmlFragment + htmlEnd;
			Debug.WriteLine(cf_html);
			dataObject.SetText(cf_html, TextDataFormat.Html);
		}

19 Source : HeightTree.cs
with MIT License
from Abdesol

public void RebuildDoreplacedent()
		{
			foreach (CollapsedLineSection s in GetAllCollapsedSections()) {
				s.Start = null;
				s.End = null;
			}

			HeightTreeNode[] nodes = new HeightTreeNode[doreplacedent.LineCount];
			int lineNumber = 0;
			foreach (DoreplacedentLine ls in doreplacedent.Lines) {
				nodes[lineNumber++] = new HeightTreeNode(ls, defaultLineHeight);
			}
			Debug.replacedert(nodes.Length > 0);
			// now build the corresponding balanced tree
			int height = DoreplacedentLineTree.GetTreeHeight(nodes.Length);
			Debug.WriteLine("HeightTree will have height: " + height);
			root = BuildTree(nodes, 0, nodes.Length, height);
			root.color = BLACK;
#if DEBUG
			CheckProperties();
#endif
		}

19 Source : ExtensionMethods.cs
with MIT License
from Abdesol

[Conditional("DEBUG")]
		public static void Log(bool condition, string format, params object[] args)
		{
			if (condition) {
				string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args) + Environment.NewLine + Environment.StackTrace;
				Console.WriteLine(output);
				Debug.WriteLine(output);
			}
		}

19 Source : VisualLineTextSource.cs
with MIT License
from Abdesol

public override TextRun GetTextRun(int textSourceCharacterIndex)
		{
			try {
				foreach (VisualLineElement element in VisualLine.Elements) {
					if (textSourceCharacterIndex >= element.VisualColumn
						&& textSourceCharacterIndex < element.VisualColumn + element.VisualLength) {
						int relativeOffset = textSourceCharacterIndex - element.VisualColumn;
						TextRun run = element.CreateTextRun(textSourceCharacterIndex, this);
						if (run == null)
							throw new ArgumentNullException(element.GetType().Name + ".CreateTextRun");
						if (run.Length == 0)
							throw new ArgumentException("The returned TextRun must not have length 0.", element.GetType().Name + ".Length");
						if (relativeOffset + run.Length > element.VisualLength)
							throw new ArgumentException("The returned TextRun is too long.", element.GetType().Name + ".CreateTextRun");
						InlineObjectRun inlineRun = run as InlineObjectRun;
						if (inlineRun != null) {
							inlineRun.VisualLine = VisualLine;
							VisualLine.hasInlineObjects = true;
							TextView.AddInlineObject(inlineRun);
						}
						return run;
					}
				}
				if (TextView.Options.ShowEndOfLine && textSourceCharacterIndex == VisualLine.VisualLength) {
					return CreateTextRunForNewLine();
				}
				return new TextEndOfParagraph(1);
			} catch (Exception ex) {
				Debug.WriteLine(ex.ToString());
				throw;
			}
		}

19 Source : VisualLineTextSource.cs
with MIT License
from Abdesol

public override TextSpan<CultureSpecificCharacterBufferRange> GetPrecedingText(int textSourceCharacterIndexLimit)
		{
			try {
				foreach (VisualLineElement element in VisualLine.Elements) {
					if (textSourceCharacterIndexLimit > element.VisualColumn
						&& textSourceCharacterIndexLimit <= element.VisualColumn + element.VisualLength) {
						TextSpan<CultureSpecificCharacterBufferRange> span = element.GetPrecedingText(textSourceCharacterIndexLimit, this);
						if (span == null)
							break;
						int relativeOffset = textSourceCharacterIndexLimit - element.VisualColumn;
						if (span.Length > relativeOffset)
							throw new ArgumentException("The returned TextSpan is too long.", element.GetType().Name + ".GetPrecedingText");
						return span;
					}
				}
				CharacterBufferRange empty = CharacterBufferRange.Empty;
				return new TextSpan<CultureSpecificCharacterBufferRange>(empty.Length, new CultureSpecificCharacterBufferRange(null, empty));
			} catch (Exception ex) {
				Debug.WriteLine(ex.ToString());
				throw;
			}
		}

19 Source : SelectionMouseHandler.cs
with MIT License
from Abdesol

[System.Diagnostics.Codereplacedysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
		void textArea_Drop(object sender, DragEventArgs e)
		{
			try {
				DragDropEffects effect = GetEffect(e);
				e.Effects = effect;
				if (effect != DragDropEffects.None) {
					int start = textArea.Caret.Offset;
					if (mode == MouseSelectionMode.Drag && textArea.Selection.Contains(start)) {
						Debug.WriteLine("Drop: did not drop: drop target is inside selection");
						e.Effects = DragDropEffects.None;
					} else {
						Debug.WriteLine("Drop: insert at " + start);

						var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText);
						textArea.RaiseEvent(pastingEventArgs);
						if (pastingEventArgs.CommandCancelled)
							return;

						string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea);
						if (text == null)
							return;
						bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType);

						// Mark the undo group with the currentDragDescriptor, if the drag
						// is originating from the same control. This allows combining
						// the undo groups when text is moved.
						textArea.Doreplacedent.UndoStack.StartUndoGroup(this.currentDragDescriptor);
						try {
							if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) {

							} else {
								textArea.Doreplacedent.Insert(start, text);
								textArea.Selection = Selection.Create(textArea, start, start + text.Length);
							}
						} finally {
							textArea.Doreplacedent.UndoStack.EndUndoGroup();
						}
					}
					e.Handled = true;
				}
			} catch (Exception ex) {
				OnDragException(ex);
			}
		}

19 Source : SelectionMouseHandler.cs
with MIT License
from Abdesol

void StartDrag()
		{
			// mouse capture and Drag'n'Drop doesn't mix
			textArea.ReleaseMouseCapture();

			// prevent nested StartDrag calls
			mode = MouseSelectionMode.Drag;

			DataObject dataObject = textArea.Selection.CreateDataObject(textArea);

			DragDropEffects allowedEffects = DragDropEffects.All;
			var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Doreplacedent, s)).ToList();
			foreach (ISegment s in deleteOnMove) {
				ISegment[] result = textArea.GetDeletableSegments(s);
				if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) {
					allowedEffects &= ~DragDropEffects.Move;
				}
			}

			var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true);
			textArea.RaiseEvent(copyingEventArgs);
			if (copyingEventArgs.CommandCancelled)
				return;

			object dragDescriptor = new object();
			this.currentDragDescriptor = dragDescriptor;

			DragDropEffects resultEffect;
			using (textArea.AllowCaretOutsideSelection()) {
				var oldCaretPosition = textArea.Caret.Position;
				try {
					Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects);
					resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects);
					Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect);
				} catch (COMException ex) {
					// ignore COM errors - don't crash on badly implemented drop targets
					Debug.WriteLine("DoDragDrop failed: " + ex.ToString());
					return;
				}
				if (resultEffect == DragDropEffects.None) {
					// reset caret if drag was aborted
					textArea.Caret.Position = oldCaretPosition;
				}
			}

			this.currentDragDescriptor = null;

			if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) {
				bool draggedInsideSingleDoreplacedent = (dragDescriptor == textArea.Doreplacedent.UndoStack.LastGroupDescriptor);
				if (draggedInsideSingleDoreplacedent)
					textArea.Doreplacedent.UndoStack.StartContinuedUndoGroup(null);
				textArea.Doreplacedent.BeginUpdate();
				try {
					foreach (ISegment s in deleteOnMove) {
						textArea.Doreplacedent.Remove(s.Offset, s.Length);
					}
				} finally {
					textArea.Doreplacedent.EndUpdate();
					if (draggedInsideSingleDoreplacedent)
						textArea.Doreplacedent.UndoStack.EndUndoGroup();
				}
			}
		}

19 Source : TextArea.cs
with MIT License
from Abdesol

void EnsureSelectionValid()
		{
			ensureSelectionValidRequested = false;
			if (allowCaretOutsideSelection == 0) {
				if (!selection.IsEmpty && !selection.Contains(caret.Offset)) {
					Debug.WriteLine("Resetting selection because caret is outside");
					this.ClearSelection();
				}
			}
		}

19 Source : TextAreaAutomationPeer.cs
with MIT License
from Abdesol

private void OnSelectionChanged(object sender, EventArgs e)
		{
			Debug.WriteLine("RaiseAutomationEvent(AutomationEvents.TextPatternOnTextSelectionChanged)");
			RaiseAutomationEvent(AutomationEvents.TextPatternOnTextSelectionChanged);
		}

19 Source : TextAreaAutomationPeer.cs
with MIT License
from Abdesol

public ITextRangeProvider[] GetSelection()
		{
			Debug.WriteLine("TextAreaAutomationPeer.GetSelection()");
			if (TextArea.Selection.IsEmpty) {
				var anchor = TextArea.Doreplacedent.CreateAnchor(TextArea.Caret.Offset);
				anchor.SurviveDeletion = true;
				return new ITextRangeProvider[] { new TextRangeProvider(TextArea, TextArea.Doreplacedent, new AnchorSegment(anchor, anchor)) };
			}
			return TextArea.Selection.Segments.Select(s => new TextRangeProvider(TextArea, TextArea.Doreplacedent, s)).ToArray();
		}

19 Source : TextAreaAutomationPeer.cs
with MIT License
from Abdesol

public ITextRangeProvider[] GetVisibleRanges()
		{
			Debug.WriteLine("TextAreaAutomationPeer.GetVisibleRanges()");
			throw new NotImplementedException();
		}

19 Source : TextAreaAutomationPeer.cs
with MIT License
from Abdesol

public ITextRangeProvider RangeFromChild(IRawElementProviderSimple childElement)
		{
			Debug.WriteLine("TextAreaAutomationPeer.RangeFromChild()");
			throw new NotImplementedException();
		}

19 Source : TextAreaAutomationPeer.cs
with MIT License
from Abdesol

public ITextRangeProvider RangeFromPoint(System.Windows.Point screenLocation)
		{
			Debug.WriteLine("TextAreaAutomationPeer.RangeFromPoint()");
			throw new NotImplementedException();
		}

19 Source : TextRangeProvider.cs
with MIT License
from Abdesol

[Conditional("DEBUG")]
		static void Log(string format, params object[] args)
		{
			Debug.WriteLine(string.Format(format, args));
		}

19 Source : FastLineRenderableSeriesEx.cs
with MIT License
from ABTSoftware

protected override void InternalDraw(IRenderContext2D renderContext, IRenderPreplacedData renderPreplacedData)
        {
            base.InternalDraw(renderContext, renderPreplacedData);
            Debug.WriteLine("Drawing! Custom series...");
        }

19 Source : CustomTouchModifier.cs
with MIT License
from ABTSoftware

public override void OnModifierTouchDown(ModifierTouchArgs e)
        {
            base.OnModifierTouchDown(e);
            Debug.WriteLine("CustomTouchModifier.OnModifierTouchDown");
        }

19 Source : CustomTouchModifier.cs
with MIT License
from ABTSoftware

public override void OnModifierTouchMove(ModifierTouchArgs e)
        {
            base.OnModifierTouchMove(e);
            Debug.WriteLine("CustomTouchModifier.OnModifierTouchMove");
        }

19 Source : CustomTouchModifier.cs
with MIT License
from ABTSoftware

public override void OnModifierTouchUp(ModifierTouchArgs e)
        {
            base.OnModifierTouchUp(e);
            Debug.WriteLine("CustomTouchModifier.OnModifierTouchUp");
        }

19 Source : CustomTouchModifier.cs
with MIT License
from ABTSoftware

public override void OnModifierTouchManipulationDelta(ModifierManipulationDeltaArgs e)
        {
            base.OnModifierTouchManipulationDelta(e);
            Debug.WriteLine("CustomTouchModifier.OnModifierTouchManipulationDelta");
        }

19 Source : YAxisSameZeroLine.xaml.cs
with MIT License
from ABTSoftware

private static void OnVisibleRangeChanged(AxisBase axis, IRange newVisibleRange, string groupName)
        {
            lock (AxisByGroup)
            {
                var otherAxis = AxisByGroup[groupName].Where(a => ReferenceEquals(a, axis) == false).ToList();

                // you have this axis
                // you have this axis VisibleRange
                // you have otherAxis list 
                // now do the calculation! 
                Debug.WriteLine($"Axis with name {axis.Tag} in group {groupName} reported VisibleRange= {newVisibleRange.Min}, {newVisibleRange.Max}");
            }
        }

19 Source : SciChartTestRunner.cs
with MIT License
from ABTSoftware

public void OnChartRendered(object sender, EventArgs e)
        {
            Debug.WriteLine("Chart was rendered");
            RunNext(_duration, _testCallback, _completedCallback);
        }

19 Source : MainWindow.xaml.cs
with Apache License 2.0
from ac87

public void Output(string output, bool consoleOnly = false)
        {
            if (consoleOnly)
            {
                System.Diagnostics.Debug.WriteLine(output);
                return;
            }

            if (ListBoxOutput.Dispatcher.CheckAccess())
            {
                System.Diagnostics.Debug.WriteLine(output);

                // stop using memory for old debug lines.
                if (ListBoxOutput.Items.Count > 500)
                    ListBoxOutput.Items.RemoveAt(0);

                ListBoxOutput.Items.Add(output);
                ListBoxOutput.ScrollIntoView(ListBoxOutput.Items[ListBoxOutput.Items.Count-1]);

                if (output.StartsWith("Error") && Height == NormalHeight)
                    Height = DebugHeight;
            }
            else
                ListBoxOutput.Dispatcher.BeginInvoke(new Action(() => Output(output)));
        }

19 Source : PrimitiveMethods.Download.cs
with MIT License
from Accelerider

public static IObservable<(long Offset, int Bytes)> CreateBlockDownloadItem(
            Func<Task<(HttpWebResponse response, Stream inputStream)>> streamPairFactory,
            BlockTransferContext context) => Observable.Create<(long Offset, int Bytes)>(o =>
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var cancellationToken = cancellationTokenSource.Token;

            // Execute copy stream by async.
            Task.Run(async () =>
            {
                try
                {
                    (HttpWebResponse response, Stream outputStream) = await streamPairFactory();

                    using (response)
                    using (var inputStream = response.GetResponseStream())
                    using (outputStream)
                    {
                        byte[] buffer = new byte[128 * 1024];
                        int count;

                        Guards.ThrowIfNull(inputStream);

                        // ReSharper disable once PossibleNullReferenceException
                        while ((count = inputStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                Debug.WriteLine($"[CANCELLED] [{DateTime.Now}] BLOCK DOWNLOAD ITEM ({context.Offset})");
                                o.OnError(new BlockTransferException(context, new OperationCanceledException()));
                                return;
                            }

                            outputStream.Write(buffer, 0, count);
                            o.OnNext((context.Offset, count));
                        }
                    }

                    o.OnCompleted();
                }
                catch (Exception e)
                {
                    o.OnError(new BlockTransferException(context, e));
                }
            }, cancellationToken);

            return () =>
            {
                Debug.WriteLine($"[DISPOSED] [{DateTime.Now}] BLOCK DOWNLOAD ITEM ({context.Offset})");
                cancellationTokenSource.Cancel();
            };
        });

19 Source : MessageList.xaml.cs
with MIT License
from Accelerider

private async void LoadSubsequentMessages()
        {
            Debug.WriteLine("Gets subsequent 10 messages.");
        }

19 Source : MessageList.xaml.cs
with MIT License
from Accelerider

private async void LoadPreviousMessages()
        {
            Debug.WriteLine("Gets previous 10 messages.");
        }

19 Source : MiscUtils.cs
with GNU Lesser General Public License v3.0
from acnicholas

public static DateTime ToDateTime(string dateValue)
        {
            if (string.IsNullOrEmpty(dateValue))
            {
                return new DateTime();
            }

            var date = dateValue.Trim();
            // ReSharper disable once InconsistentNaming
            const string DateDelimiters = @"-.\/_ ";
            char[] c = DateDelimiters.ToCharArray();
            int d2 = date.LastIndexOfAny(c);
            int d1 = date.IndexOfAny(c);

            try
            {
                string year = string.Empty;
                string month = string.Empty;
                string day = string.Empty;
                if (date.Length > d2 + 1)
                {
                    year = date.Substring(d2 + 1);
                }
                if (date.Length > (d1 + 1) && (d2 - d1 - 1) < date.Length - (d1 + 1))
                {
                    month = date.Substring(d1 + 1, d2 - d1 - 1);
                }
                if (date.Length > 0 && d1 <= date.Length)
                {
                    day = date.Substring(0, d1);
                }
                return new DateTime(
                    Convert.ToInt32(year, CultureInfo.InvariantCulture),
                    Convert.ToInt32(month, CultureInfo.InvariantCulture),
                    Convert.ToInt32(day, CultureInfo.InvariantCulture));
            }
            catch (ArgumentOutOfRangeException e)
            {
                Debug.WriteLine("Error in ToDateTime:" + e.Message);
                return new DateTime();
            }
            catch (FormatException e)
            {
                Debug.WriteLine("Error in ToDateTime:" + e.Message);
                return new DateTime();
            }
            catch (OverflowException e)
            {
                Debug.WriteLine("Error in ToDateTime:" + e.Message);
                return new DateTime();
            }
        }

19 Source : MockDialogService.cs
with GNU Lesser General Public License v3.0
from acnicholas

public void ShowMessageBox(string message)
        {
            System.Diagnostics.Debug.WriteLine(message);
        }

19 Source : RoomConversionManager.cs
with GNU Lesser General Public License v3.0
from acnicholas

private bool CreateRoomMreplacedByBoundingBox(Room room)
        {
            try
            {
                var bb = room.get_BoundingBox(null);
                var eid = new ElementId(BuiltInCategory.OST_Mreplaced);

                if (bb == null) {
                    return false;
                }

#if REVIT2019 || REVIT2018 || REVIT2017 || REVIT2020 || REVIT2021 || REVIT2022
                DirectShape roomShape = DirectShape.CreateElement(doc, eid);
#else
                    DirectShape roomShape = DirectShape.CreateElement(doc, eid, "A", "B");
#endif

                var curves = new List<Curve>();

                var bl = new XYZ(bb.Min.X, bb.Min.Y, bb.Min.Z);
                var br = new XYZ(bb.Max.X, bb.Min.Y, bb.Min.Z);
                var tr = new XYZ(bb.Max.X, bb.Max.Y, bb.Min.Z);
                var tl = new XYZ(bb.Min.X, bb.Max.Y, bb.Min.Z);

                var height = bb.Max.Z - bb.Min.Z;

                curves.Add(Line.CreateBound(bl, br));
                curves.Add(Line.CreateBound(br, tr));
                curves.Add(Line.CreateBound(tr, tl));
                curves.Add(Line.CreateBound(tl, bl));
                var loop = CurveLoop.Create(curves);
                var options = new SolidOptions(ElementId.InvalidElementId, ElementId.InvalidElementId);
                var roomSolid = GeometryCreationUtilities.CreateExtrusionGeometry(new[] { loop }, new XYZ(0, 0, 1), height, options);

                if (roomSolid != null)
                {
                    var geomObj = new GeometryObject[] { roomSolid };
                    if (geomObj.Length > 0)
                    {
                        roomShape.SetShape(geomObj);
                        CopyAllRoomParametersToMreplacedes(room, roomShape);
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            return false;
        }

19 Source : SheetCopierManager.cs
with GNU Lesser General Public License v3.0
from acnicholas

public bool CreateAndPopulateNewSheet(SheetCopierViewHost host, StringBuilder summaryText)
        {
            if (host == null)
            {
                return false;
            }

            if (host.Type == ViewHostType.Model)
            {
                CreateViews(host, summaryText);
                return true;
            }

            // turn on hidden revisions, if option set
            if (Settings.Default.DeleteRevisionClouds)
            {
                foreach (Revision rev in hiddenRevisionClouds)
                {
                    try
                    {
                        rev.Visibility = RevisionVisibility.CloudAndTagVisible;
                    }
                    catch (Autodesk.Revit.Exceptions.ArgumentOutOfRangeException ex)
                    {
                        SCaddinsApp.WindowManager.ShowMessageBox(ex.Message);
                    }
                }
            }

            try
            {
                host.DestinationSheet = AddEmptySheetToDoreplacedent(
                    host.Number,
                    host.replacedle,
                    host.PrimaryCustomSheetParameter,
                    host.SecondaryCustomSheetParameter);
            }
            catch (Exception ex)
            {
                SCaddinsApp.WindowManager.ShowMessageBox(ex.Message);
                SCaddinsApp.WindowManager.ShowMessageBox(ex.StackTrace);
            }

            if (host.DestinationSheet != null)
            {
                CreateViews(host, summaryText);
            }
            else
            {
                return false;
            }

            try
            {
                CopyElementsBetweenSheets(host);
            }
            catch (InvalidOperationException e)
            {
                Debug.WriteLine(e.Message);
            }

            if (Settings.Default.DeleteRevisionClouds)
            {
                foreach (Revision rev in hiddenRevisionClouds)
                {
                    rev.Visibility = RevisionVisibility.Hidden;
                }
            }

            var oldNumber = host.SourceSheet.SheetNumber;
            var msg = " Sheet: " + oldNumber + " copied to: " + host.Number;
            if (summaryText != null)
            {
                summaryText.Append(msg + Environment.NewLine);
            }

            return true;
        }

19 Source : SpellChecker.cs
with GNU Lesser General Public License v3.0
from acnicholas

private List<CorrectionCandidate> GetAllTextParameters(Doreplacedent doc)
        {
            var candidates = new List<CorrectionCandidate>();
            var collector = new FilteredElementCollector(doc).WhereElementIsNotElementType();

            // Get TextNote Elements
            candidates.AddRange(GetTextNoteElements(doc));

            foreach (Element element in collector)
            {
                var parameterSet = element.Parameters;
                if (parameterSet == null || parameterSet.IsEmpty) {
                    continue;
                }
                foreach (var parameter in parameterSet)
                {
                    if (parameter is Autodesk.Revit.DB.Parameter)
                    {
                        Autodesk.Revit.DB.Parameter p = (Autodesk.Revit.DB.Parameter)parameter;
                        if (p == null || !p.HasValue) {
                            continue;
                        }
                        if (p.IsReadOnly) {
                            continue;
                        }
                        try
                        {
                            if (p.StorageType == StorageType.String)
                            {
                                var rc = new CorrectionCandidate(p, hunspell, ref autoReplacementList);

                                if (!string.IsNullOrEmpty(rc.OriginalText))
                                {
                                    candidates.Add(rc);
                                }
                            }
                        }
                        catch (System.Exception e)
                        {
                            System.Diagnostics.Debug.WriteLine(e.Message);
                        }
                    }
                }
            }
            return candidates;
        }

19 Source : CameraFromViewCommand.cs
with GNU Lesser General Public License v3.0
from acnicholas

public static BoundingBoxXYZ SectionViewExtentsBoundingBox(UIView view)
        {
            if (view == null)
            {
                return new BoundingBoxXYZ();
            }
            BoundingBoxXYZ result = new BoundingBoxXYZ();
            try
            {
                XYZ min = new XYZ(view.GetZoomCorners()[0].X, view.GetZoomCorners()[0].Y, view.GetZoomCorners()[0].Z - 4);
                XYZ max = new XYZ(view.GetZoomCorners()[1].X, view.GetZoomCorners()[1].Y, view.GetZoomCorners()[1].Z + 4);
                result.set_Bounds(0, min);
                result.set_Bounds(1, max);
            }
            catch (ArgumentException ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                result.Dispose();
                return null;
            }
            return result;
        }

See More Examples