#collections in CSharp
Explore tagged Tumblr posts
Text
Mastering C# Collections: Enhance Your Coding Skills and Streamline Data Management
As a developer, it is essential to have a solid understanding of data management in programming languages. In C#, collections play a crucial role in efficiently organizing and manipulating data. Collections are containers that allow you to store and retrieve multiple values of the same or different types. They provide powerful ways to manage data, improve code readability, and enhance overall coding skills.
Benefits of using collections in C
Using collections in C# offers several benefits that contribute to better coding practices and streamlined data management. Firstly, collections provide a structured approach to store and organize data, making it easier to access and manipulate specific elements. Unlike traditional arrays, collections offer dynamic resizing, allowing you to add or remove elements as needed, without worrying about size limitations.
Secondly, collections provide a wide range of built-in methods and properties that simplify common data operations. For example, you can easily sort, filter, or search elements within a collection using predefined methods. This saves time and effort in writing custom algorithms for such operations.
Thirdly, collections support type safety, ensuring that you can only store elements of specific types within a collection. This helps prevent runtime errors and enhances code reliability. Additionally, collections allow you to iterate over elements using loops, making it easier to perform batch operations or apply transformations to each element.
Understanding different collection types in C
C# offers a variety of collection types, each designed for specific use cases. Let's explore some of the most commonly used collection types in C# and understand their characteristics:
Arrays: Arrays are the most basic collection type in C#. They provide a fixed-size structure to store elements of the same type. Arrays offer efficient memory allocation and fast access to elements, but they lack dynamic resizing capabilities.
Lists: Lists, represented by the List<T> class, are dynamic collections that can grow or shrink based on the number of elements. They provide methods to add, remove, or modify elements at any position within the list. Lists are widely used due to their flexibility and ease of use.
Dictionaries: Dictionaries, represented by the Dictionary<TKey, TValue> class, store key-value pairs. They enable fast retrieval of values based on a unique key. Dictionaries are ideal for scenarios where you need to quickly access elements by their associated keys.
Sets: Sets, represented by the HashSet<T> class, store unique elements without any specific order. They provide methods to add, remove, or check for the existence of elements efficiently. Sets are useful when you need to perform operations like union, intersection, or difference between multiple collections.
Queues: Queues, represented by the Queue<T> class, follow the First-In-First-Out (FIFO) principle. Elements are added to the end of the queue and removed from the front, maintaining the order of insertion. Queues are commonly used in scenarios where you need to process items in the order of their arrival.
Stacks: Stacks, represented by the Stack<T> class, follow the Last-In-First-Out (LIFO) principle. Elements are added to the top of the stack and removed from the same position. Stacks are useful when you need to implement algorithms like depth-first search or undo/redo functionality.
Exploring C# generic collections
C# also provides a powerful feature called generic collections, which allow you to create strongly typed collections. Generic collections are parameterized with a specific type, ensuring type safety and eliminating the need for explicit type casting. Let's explore some commonly used generic collection types in C#:
List: Generic lists provide the flexibility of dynamically resizing collections while ensuring type safety. You can create a list of any type by specifying the desired type within angle brackets. For example, List<int> represents a list of integers, and List<string> represents a list of strings.
Dictionary: Generic dictionaries store key-value pairs, similar to non-generic dictionaries. However, generic dictionaries provide type safety and better performance. You can specify the types of keys and values when creating a dictionary. For example, Dictionary<string, int> represents a dictionary with string keys and integer values.
HashSet: Generic hash sets store unique elements without any specific order. They provide efficient lookup, insertion, and removal operations. You can create a hash set of any type by specifying the desired type within angle brackets. For example, HashSet<string> represents a hash set of strings.
Queue: Generic queues follow the First-In-First-Out (FIFO) principle, similar to non-generic queues. They ensure type safety and provide methods to enqueue and dequeue elements. You can create a queue of any type by specifying the desired type within angle brackets. For example, Queue<int> represents a queue of integers.
Stack: Generic stacks follow the Last-In-First-Out (LIFO) principle, similar to non-generic stacks. They ensure type safety and provide methods to push and pop elements. You can create a stack of any type by specifying the desired type within angle brackets. For example, Stack<string> represents a stack of strings.
By utilizing generic collections, you can write cleaner and more robust code, eliminating potential runtime errors and enhancing code maintainability.
Sample C# codes for working with collections
To illustrate the usage of collections in C#, let's explore some sample code snippets that demonstrate common operations:
Working with Lists:
List<string> fruits = new List<string>();
fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Orange");
Console.WriteLine("Total fruits: " + fruits.Count);
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
if (fruits.Contains("Apple"))
{
Console.WriteLine("Apple is present in the list.");
}
fruits.Remove("Banana");
Console.WriteLine("Total fruits after removing Banana: " + fruits.Count);
Working with Dictionaries:
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("John", 25);
ages.Add("Emily", 30);
ages.Add("Michael", 35);
Console.WriteLine("Age of John: " + ages["John"]);
foreach (KeyValuePair<string, int> entry in ages)
{
Console.WriteLine(entry.Key + ": " + entry.Value);
}
if (ages.ContainsKey("Emily"))
{
Console.WriteLine("Emily's age: " + ages["Emily"]);
}
ages.Remove("Michael");
Console.WriteLine("Total entries after removing Michael: " + ages.Count);
These code snippets demonstrate basic operations like adding elements, iterating over collections, checking for element existence, and removing elements. Modify and experiment with these code snippets to understand the behavior of different collection types and their methods.
Examples of common use cases for collections in C
Collections in C# find applications in various scenarios. Let's explore some common use cases where collections prove to be invaluable:
Data storage and retrieval: Collections provide a convenient way to store and retrieve data. For example, you can use a list to store a collection of customer details, a dictionary to store key-value pairs representing configuration settings, or a queue to manage incoming requests.
Sorting and searching: Collections offer built-in methods for sorting and searching elements. You can easily sort a list of objects based on specific properties or search for elements that meet certain criteria. Collections eliminate the need for writing complex sorting or searching algorithms from scratch.
Batch processing and transformations: Collections allow you to iterate over elements using loops, enabling batch processing and transformations. For example, you can apply a discount to each item in a list, convert a list of strings to uppercase, or filter out elements based on specific conditions.
Efficient memory management: Collections provide dynamic resizing capabilities, ensuring efficient memory utilization. Unlike arrays, which have a fixed size, collections automatically resize themselves based on the number of elements. This prevents unnecessary memory allocation or wastage.
Concurrency and thread safety: Collections in C# offer thread-safe alternatives, ensuring safe access and manipulation of data in multi-threaded environments. For example, the ConcurrentDictionary<TKey, TValue> class provides thread-safe operations for dictionary-like functionality.
By leveraging the power of collections, you can simplify complex data management tasks, improve code readability, and enhance the overall efficiency of your C# applications.
Comparing C# collection vs list
One common question that arises when working with collections in C# is the difference between a collection and a list. While a list is a specific type of collection, there are some key distinctions to consider:
Collections: In C#, the term "collection" refers to a general concept of a container that stores and organizes data. Collections encompass various types like arrays, lists, dictionaries, sets, queues, and stacks. Collections provide a higher-level abstraction for data management and offer a range of operations and properties that can be applied to different scenarios.
List: A list, on the other hand, is a specific type of collection provided by the List<T> class in C#. It offers dynamic resizing capabilities, allowing you to add or remove elements as needed. Lists provide methods to insert, remove, or modify elements at any position within the list. Lists are commonly used due to their flexibility and ease of use.
In summary, a list is a type of collection that offers dynamic resizing and additional methods for element manipulation. Collections, on the other hand, encompass a broader range of container types, each designed for specific use cases.
Best practices for efficient data management using collections
To utilize collections effectively and ensure efficient data management in C#, consider the following best practices:
Choose the appropriate collection type: Select the collection type that best suits your specific use case. Consider factors like data size, performance requirements, element uniqueness, and the need for sorting or searching operations. Choosing the right collection type can significantly impact the efficiency of your code.
Use generics for type safety: Whenever possible, utilize generic collections to ensure type safety. By specifying the type of elements stored in a collection, you can eliminate potential runtime errors and improve code maintainability. Generic collections also eliminate the need for explicit type casting.
Prefer foreach loops for iteration: When iterating over elements in a collection, prefer the foreach loop over traditional indexing with a for loop. Foreach loops provide a more concise syntax and handle underlying details like bounds checking and iteration logic automatically.
Consider performance implications: Be mindful of performance implications, especially when dealing with large data sets. For example, using a List<T> for frequent insertions or removals at the beginning of the list may result in poor performance. In such cases, consider using a LinkedList<T> or other suitable collection type.
Dispose disposable collections: If you are using collections that implement the IDisposable interface, ensure proper disposal to release any unmanaged resources. Wrap the usage of such collections in a using statement or manually call the Dispose() method when you are done working with them.
By following these best practices, you can optimize your code for efficient data management and enhance the overall performance of your C# applications.
Advanced techniques for optimizing collection performance
While collections in C# are designed to provide efficient data management out of the box, there are advanced techniques you can employ to further optimize collection performance:
Preallocate collection size: If you know the approximate number of elements that will be stored in a collection, consider preallocating the size using the constructor or the Capacity property. This eliminates unnecessary resizing operations and improves performance.
Avoid unnecessary boxing and unboxing: Boxing and unboxing operations, where value types are converted to reference types and vice versa, can impact performance. Whenever possible, use generic collections to store value types directly, eliminating the need for boxing and unboxing.
Implement custom equality comparers: If you are working with collections that require custom equality checks, consider implementing custom equality comparers. By providing a specialized comparison logic, you can improve the performance of operations like searching, sorting, or removing elements.
Use parallel processing: In scenarios where you need to perform computationally intensive operations on collection elements, consider utilizing parallel processing techniques. C# provides the Parallel class and related constructs to parallelize operations, taking advantage of multi-core processors.
Profile and optimize: Regularly profile your code to identify performance bottlenecks. Use tools like profilers to measure execution times and memory usage. Once identified, optimize the critical sections of your code by employing appropriate algorithms or data structures.
By employing these advanced techniques, you can further enhance the performance of your C# collections and optimize your code for maximum efficiency.
Conclusion and next steps for mastering C# collections
In this article, we explored the world of C# collections and their significance in enhancing your coding skills and streamlining data management. We discussed the benefits of using collections in C#, understanding different collection types, and explored generic collections for strong typing. We also provided sample code snippets and examples of common use cases for collections.
Furthermore, we compared collections to lists, outlined best practices for efficient data management, and explored advanced techniques for optimizing collection performance. By following these guidelines, you can harness the full power of C# collections and elevate your coding skills to the next level.
To master C# collections, continue practicing with different types of collections, experiment with advanced scenarios, and explore additional features and methods provided by the .NET framework. Keep exploring the vast possibilities offered by collections, and strive to write clean, efficient, and maintainable code.
Start your journey to mastering C# collections today and witness the transformation in your coding skills and data management capabilities.
Next Steps: To further enhance your skills and understanding of C# collections, consider exploring the official Microsoft documentation on .NET collections and data structures. Additionally, practice implementing collections in real-world scenarios and collaborate with fellow developers to exchange ideas and best practices. Happy coding!
0 notes
Text
very good article discussing how do we think of garbage collection, and what function does it perform in our code
0 notes
Text

@bbc6music-blog
🦇
🪷 🐼
Sure, let's integrate both the English and Chinese descriptions along with the C# code for your "Raz A Ghul's Practical Guide to Kung Fu: Expanded Edition." After this setup, the material will be ready for publishing.
### Final Compilation: English and Chinese Descriptions with C# Code
**English Description:**
Raz A Ghul's Practical Guide to Kung Fu: Expanded Edition offers a comprehensive approach for both warriors and civilians. It includes traditional Kung Fu techniques, the innovative "Pinwheel Method" for psyche center activation, and specified tasks within a mystical forest setting. Warriors must retrieve a significant token from dangerous species, showcasing their bravery and skills. Civilians collect personal tokens that symbolize their journey and understanding of nature.
**Chinese Description (中文描述):**
《拉斯·阿·古尔的实用功夫指南:扩展版》为战士和平民提供了全面的方法。它包括传统的功夫技巧,创新的“风车法”激活心灵中心,以及在神秘森林环境中指定的任务。战士必须从危险物种中取回重要的标记,展示他们的勇气和技能。平民收集代表他们的旅程和对自然理解的个人标记。
**C# Code:**
```csharp
using System;
public class KungFuGuide
{
public string ParticipantType { get; set; }
public string TaskDescription { get; set; }
public string TokenDescription { get; set; }
public void DisplayTaskDetails()
{
Console.WriteLine($"Participant Type: {ParticipantType}");
Console.WriteLine($"Task Description: {TaskDescription}");
Console.WriteLine($"Token Description: {TokenDescription}");
}
public void PerformBreathingExercise()
{
Console.WriteLine("Starting Breathing Exercise:");
Console.WriteLine("1. Adopt the correct posture, whether sitting or standing, ensuring natural alignment and balance.");
Console.WriteLine("2. Inhale deeply, drawing energy upward from the earth through the root to the crown, visualizing it passing through each chakra.");
Console.WriteLine("3. Exhale, imagine the energy expanding outward, spinning through each chakra like a pinwheel, enhancing both spatial and self-awareness.");
}
}
class Program
{
static void Main()
{
var warriorTask = new KungFuGuide
{
ParticipantType = "Warrior",
TaskDescription = "Retrieve a significant token from a dangerous species in the mystical forest, reflecting bravery and skill.",
TokenDescription = "The token must be meaningful, demonstrating the dangers overcome, and is to be presented to the Empress."
};
var civilianTask = new KungFuGuide
{
ParticipantType = "Civilian",
TaskDescription = "Collect any meaningful or aesthetically pleasing token from the forest.",
TokenDescription = "The token represents personal growth and understanding, used to earn sashes."
};
Console.WriteLine("Warrior Task Details:");
warriorTask.DisplayTaskDetails();
warriorTask.PerformBreathingExercise();
Console.WriteLine("\nCivilian Task Details:");
civilianTask.DisplayTaskDetails();
civilianTask.PerformBreathingExercise();
}
}
```
This compilation integrates the detailed descriptions in both English and Chinese with the C# program to provide a complete and ready-to-publish manuscript for your guide. The code reflects the content described, establishing a practical and interactive experience for readers and practitioners. This setup ensures that the book is culturally inclusive and technically robust, suitable for a global audience interested in Kung Fu.
1 note
·
View note
Text
Collecte de Fonds: Une Approche Complète pour Réussir Votre Projet
La collecte de fonds est une étape cruciale pour de nombreuses associations, écoles et projets personnels. Que vous cherchiez à soutenir une cause noble, financer un projet scolaire ou aider une église, savoir comment demander des dons efficacement peut faire toute la différence. Dans ce blog, nous allons explorer divers aspects de la collecte de fonds et fournir des modèles de lettres pour faire un don à une association, demander des dons pour une église, et bien plus encore. Nous aborderons également comment gagner de l'argent pour un projet scolaire, utiliser des plateformes de financement participatif, et mettre en place une cagnotte sur Instagram.
Modèle de Lettre pour Faire un Don à une Association
Rédiger une lettre pour solliciter des dons peut sembler intimidant, mais avec un modèle bien structuré, vous pouvez capter l'attention de vos potentiels donateurs. Voici un exemple :
csharp
Copy code
[Nom de l'association]
[Adresse]
[Code postal, Ville]
[Nom du donateur]
[Adresse du donateur]
[Code postal, Ville]
[Date]
Objet : Demande de don pour [Nom de l'association]
Madame, Monsieur,
Nous faisons appel à votre générosité pour soutenir notre association [Nom de l'association] qui œuvre depuis [année] pour [cause ou objectif de l'association]. Votre don permettra de financer [détail des projets ou des actions spécifiques].
En espérant pouvoir compter sur votre soutien, nous vous prions d'agréer, Madame, Monsieur, l'expression de nos salutations distinguées.
[Signature]
Lettre de Demande de Don pour une Église
Les églises jouent un rôle essentiel dans nos communautés, et leur fonctionnement dépend souvent des dons. Voici un modèle de lettre pour demander des dons pour une église :
[Nom de l'église]
[Adresse]
[Code postal, Ville]
[Nom du donateur]
[Adresse du donateur]
[Code postal, Ville]
[Date]
Objet : Appel aux dons pour [Nom de l'église]
Cher [Nom du donateur],
En cette période de [saison ou événement spécifique], nous faisons appel à votre générosité pour soutenir [Nom de l'église]. Votre don permettra de financer [détail des projets ou des actions spécifiques de l'église].
Nous vous remercions par avance pour votre soutien précieux.
Bien à vous,
[Signature]
Comment Gagner de l'Argent pour un Projet Scolaire
Financer un projet scolaire peut être un défi, mais avec les bonnes stratégies, vous pouvez réussir. Voici quelques idées pour gagner de l'argent :
Vente de produits : Organisez une vente de gâteaux, de livres ou d'artisanat réalisé par les élèves.
Événements de collecte de fonds : Organisez un spectacle, une course sponsorisée ou une soirée à thème.
Plateformes de financement participatif : Utilisez des sites comme WhyDonate ou Leetchi pour récolter des fonds en ligne.
Demande de Don d'Argent
Pour une demande de don d'argent réussie, il est important de personnaliser votre message et de montrer clairement l'impact du don. Voici un exemple de lettre :
[Votre nom]
[Adresse]
[Code postal, Ville]
[Nom du donateur]
[Adresse du donateur]
[Code postal, Ville]
[Date]
Objet : Demande de don pour [projet ou cause]
Madame, Monsieur,
Je me permets de vous contacter afin de solliciter votre soutien financier pour [détail du projet ou de la cause]. Votre contribution permettra de [expliquer l'impact du don].
En vous remerciant par avance pour votre générosité, je vous prie d'agréer, Madame, Monsieur, l'expression de mes salutations distinguées.
[Signature]
Plateforme de Financement Participatif
Les plateformes de financement participatif sont devenues des outils indispensables pour lever des fonds. Voici quelques conseils pour utiliser ces plateformes efficacement :
Choisissez la bonne plateforme : En Belgique, des sites comme WhyDonate ou Crowdfunding Belgium sont populaires.
Créez une campagne attrayante : Utilisez des images, des vidéos et des descriptions détaillées pour attirer les donateurs.
Partagez votre campagne : Utilisez les réseaux sociaux, les emails et les événements pour promouvoir votre campagne.
Financement Participatif en Belgique
Le financement participatif Belgique est en pleine croissance. Les plateformes belges offrent des solutions adaptées aux besoins locaux et permettent de récolter des fonds pour une variété de projets. Que ce soit pour une start-up, une association ou un projet personnel, le financement participatif est une option à considérer.
Comment Rédiger une Lettre d'Appel aux Dons
Une lettre d'appel aux dons doit être persuasive et bien structurée. Voici quelques éléments clés à inclure :
Introduction : Présentez-vous et expliquez la cause ou le projet.
Objectif : Indiquez clairement ce que vous espérez accomplir avec les fonds récoltés.
Impact : Montrez comment les dons feront une différence concrète.
Appel à l'action : Incitez le lecteur à agir immédiatement.
Action Association Parents d'Élèves
Les associations de parents d'élèves jouent un rôle vital dans les écoles. Organiser des actions de collecte de fonds peut aider à financer des activités scolaires, des voyages éducatifs, et des projets d'infrastructure. Voici quelques idées :
Vente de produits : Vente de calendriers, de vêtements personnalisés ou de fournitures scolaires.
Événements sociaux : Organisez des loteries, des kermesses ou des soirées dansantes.
Partenariats locaux : Collaborez avec des entreprises locales pour obtenir des parrainages ou des dons en nature.
Comment Mettre une Cagnotte sur Instagram
Instagram est une plateforme puissante pour collecter des fonds. Voici comment mettre en place une cagnotte sur Instagram :
Utilisez les Stories : Ajoutez un sticker de lien pour diriger vos followers vers votre page de collecte de fonds.
Postez régulièrement : Partagez des mises à jour sur l'avancement de votre collecte de fonds.
Engagez votre audience : Utilisez des sondages, des Q&A, et des hashtags pour encourager l'interaction.
Modèle de Lettre pour Demande de Dons
Voici un autre modèle de lettre pour demander des dons, adaptable à différentes causes :
csharp
Copy code
[Nom de l'organisation]
[Adresse]
[Code postal, Ville]
[Nom du donateur]
[Adresse du donateur]
[Code postal, Ville]
[Date]
Objet : Demande de soutien financier pour [nom du projet ou de la cause]
Cher [Nom du donateur],
Nous faisons appel à votre générosité pour soutenir [détail du projet ou de la cause]. Votre contribution permettra de [expliquer l'impact du don].
Merci pour votre soutien.
Sincèrement,
[Signature]
Comment Faire un Don sur Twitch
Twitch est une plateforme populaire pour les diffusions en direct, et de nombreux streamers utilisent Twitch pour collecter des fonds. Voici comment faire un don sur Twitch :
Trouvez le streamer : Recherchez le streamer que vous souhaitez soutenir.
Utilisez le bouton de don : Cliquez sur le bouton de don ou de contribution sur la page du streamer.
Suivez les instructions : Entrez le montant que vous souhaitez donner et complétez le processus de paiement.
Conclusion
La collecte de fonds est une tâche essentielle pour de nombreuses causes et projets. En utilisant les bons outils et en suivant des stratégies éprouvées, vous pouvez maximiser vos chances de succès. Que ce soit par le biais de lettres de demande de dons, de plateformes de financement participatif, ou de cagnottes sur les réseaux sociaux, chaque méthode a ses avantages. N'oubliez pas de toujours remercier vos donateurs et de leur montrer l'impact de leur contribution. Avec détermination et créativité, vous pouvez atteindre vos objectifs de collecte de fonds et réaliser vos projets.
Keywords; collecte de fonds, modèle de lettre pour faire un don à une association, lettre de demande de don pour une église, comment gagner de l'argent pour un projet scolaire, demande de don d'argent, plateforme de financement participatif, financement participatif belgique, comment rédiger une lettre d'appel, action association parents d'élèves, comment mettre une cagnotte sur instagram, modèle de lettre pour demande de dons, comment faire un don sur twitch
#collecte de fonds#modèle de lettre pour faire un don à une association#lettre de demande de don pour une église#comment gagner de l'argent pour un projet scolaire#demande de don d'argent#plateforme de financement participatif#financement participatif belgique#comment rédiger une lettre d'appel#action association parents d'élèves#comment mettre une cagnotte sur instagram#modèle de lettre pour demande de dons#comment faire un don sur twitch
0 notes
Text
🌟 Welcome to the World of C# Programming with Markcraft Solutions!🌟
Hey there, aspiring coders! 👋 Are you ready to dive into the exciting realm of C# programming? Join us at Markcraft Solutions for an epic journey into the fundamentals of C# and unleash your coding potential! 💻✨
In our Introductory C# Programming course, you'll embark on a thrilling adventure where you'll learn the basics of C# syntax, data types, control structures, and more. 💡 Whether you're a beginner eager to kickstart your coding journey or a seasoned developer looking to sharpen your skills, our course is tailored just for you!
At Markcraft Solutions, we believe in hands-on learning and interactive experiences. 🤝 Get ready to roll up your sleeves and dive into practical coding exercises and real-world projects that will challenge and inspire you. 💪🚀
Join our vibrant community of learners, where you'll have the opportunity to connect with fellow enthusiasts, share insights, and grow together as aspiring developers. 🌱💬
Don't miss out on this incredible opportunity to level up your coding skills and unleash your creativity with C#! Enroll now and let's embark on this coding odyssey together! 🚀🌟 #CSharp #Programming #MarkcraftSolutions #BeginnerFriendly #CodeYourDreams
0 notes
Text
Hire .NET Developers: A Practical Guide to Machine Learning in .NET
Machine learning (ML) has become a transformative force in the realm of technology, allowing systems to learn and adapt from data without explicit programming. While traditionally associated with languages like Python and R, the .NET ecosystem has made significant strides in integrating machine learning capabilities, providing developers, including those you might want to hire .NET developers, with powerful tools for building intelligent applications. In this practical guide, we'll explore the landscape of machine learning in .NET, covering key libraries, frameworks, and practical examples to get you started on your machine learning journey. This is particularly relevant for businesses looking to expand their team and hire .NET developers with a skill set that extends to machine learning applications.
Understanding the Basics
Before delving into the specifics of machine learning in .NET, let's briefly touch upon the foundational concepts. Machine learning involves training models on data to make predictions or decisions without being explicitly programmed. The process typically includes data collection, model training, evaluation, and deployment.
ML.NET: The Machine Learning Library for .NET
At the heart of .NET's machine learning capabilities lies ML.NET, an open-source and cross-platform machine learning framework developed by Microsoft. ML.NET is not only a powerful tool for incorporating machine learning into applications but also a valuable asset when seeking to hire .NET developers for your projects. This framework enables developers to seamlessly integrate machine learning functionalities into their .NET applications, making it an attractive skill set for businesses looking to expand their teams and hire .NET developers with expertise in diverse ML tasks, including classification, regression, clustering, and anomaly detection. Embracing ML.NET not only enhances your application's intelligence but also opens up opportunities to bring in skilled professionals as you embark on your journey to hire .NET developers with a flair for machine learning.
Installation and Setup
To get started with ML.NET, you need to install the ML.NET NuGet package. Once installed, you can leverage the capabilities of this powerful machine learning framework within your .NET projects. Whether you are working with the traditional .NET Framework or the more recent .NET Core/5/6 applications, ML.NET ensures compatibility and flexibility. This versatility makes it an ideal choice for projects handled by a skilled Best .NET development company looking to integrate machine learning capabilities. If you are planning to incorporate advanced machine learning features into your applications and considering outsourcing, partnering with a reputable best .NET development company can provide the expertise needed to navigate the intricacies of ML.NET seamlessly. The support for both traditional and modern .NET platforms further extends the possibilities when deciding to collaborate with a proficient Best .NET development company for your software projects.
bash
dotnet add package Microsoft.ML
Building Your First Model
Let's dive into a simple example to understand how to build a basic ML.NET model. Consider a scenario where you want to predict housing prices based on features like square footage, number of bedrooms, and location. ML.NET uses a pipeline-based approach, making it intuitive for developers.
csharp
// Define a class to hold data
public class HouseData
{
public float Size { get; set; }
public int Bedrooms { get; set; }
public float Price { get; set; }
}
// Create an MLContext
var context = new MLContext();
// Load the data
var data = context.Data.LoadFromTextFile<HouseData>("path/to/your/data.csv", separatorChar: ',');
// Define the pipeline
var pipeline = context.Transforms.Conversion.MapValueToKey("Label", "Price")
.Append(context.Transforms.Concatenate("Features", "Size", "Bedrooms"))
.Append(context.Transforms.NormalizeMinMax("Features"))
.Append(context.Transforms.Conversion.MapKeyToValue("Price"));
// Train the model
var model = pipeline.Fit(data);
This simple example demonstrates loading data, defining features, and training a model using ML.NET's pipeline.
Integration with TensorFlow and ONNX
While ML.NET provides a broad set of capabilities, it also acknowledges the diversity of the machine learning landscape. Through TensorFlow and ONNX (Open Neural Network Exchange) integration, developers can leverage pre-trained models from popular frameworks seamlessly.
TensorFlow Integration
ML.NET's TensorFlow integration enables the use of TensorFlow models directly within .NET applications. This is particularly useful when you have a pre-trained TensorFlow model and want to incorporate it into your .NET project for tasks such as image recognition or natural language processing.
ONNX Support
ONNX is an open format for representing deep learning models. ML.NET's support for ONNX allows you to use models created in other frameworks like PyTorch or scikit-learn within your .NET applications, promoting interoperability across the machine learning ecosystem.
Model Evaluation and Metrics
Once you've trained your machine learning model, it's crucial to evaluate its performance. ML.NET provides various metrics for classification, regression, and clustering tasks, allowing you to assess the accuracy and effectiveness of your models. For businesses aiming to streamline this process and ensure optimal performance, it becomes imperative to consider the expertise of skilled professionals. This is where the role of experienced .NET developers comes into play.
When you hire .NET developers with proficiency in machine learning and ML.NET, you gain a strategic advantage in model evaluation and fine-tuning. Seasoned .NET developers possess the knowledge to interpret these metrics effectively, making informed decisions to enhance model accuracy and overall performance. Their expertise extends beyond just coding; they contribute significantly to the iterative process of refining machine learning models for optimal results.
Therefore, when evaluating the performance of your machine learning models in a .NET environment, considering the insights and contributions of expert .NET developers becomes a valuable asset. Their skill set ensures that your models not only meet performance expectations but also pave the way for continuous improvement. If you're looking to elevate your machine learning endeavors within the .NET ecosystem, don't hesitate to explore the option to hire .NET developers with a strong foundation in both development and machine learning evaluation.
csharp
var predictions = model.Transform(data);
var metrics = context.Regression.Evaluate(predictions);
Console.WriteLine($"R-Squared: {metrics.RSquared}");
Console.WriteLine($"Mean Absolute Error: {metrics.MeanAbsoluteError}");
These metrics provide insights into how well your model is performing on the given data.
Deployment Options
After successfully training and evaluating your model, the next step is deployment. ML.NET supports various deployment options, including integration with Azure Machine Learning for scalable and cloud-based solutions.
Conclusion
In this practical guide, we've scratched the surface of machine learning in .NET using the ML.NET framework. From understanding the basics to building and evaluating models, the .NET ecosystem offers a robust set of tools for developers venturing into the exciting field of machine learning. Whether you're working on predictive analytics, image recognition, or natural language processing, exploring the integration of machine learning in .NET opens up new possibilities for creating intelligent and adaptive applications.
Remember, the best way to master machine learning in .NET is through hands-on experience. So, if you're looking to expedite your journey into the world of machine learning and seeking expert guidance, consider partnering with a skilled Best .NET development company. Collaborating with a proficient Best .NET development company not only provides access to seasoned professionals but also ensures that your projects involving machine learning integration are executed with precision and expertise. So, roll up your sleeves, dive into the code, and let your journey into the world of machine learning with .NET begin with the support of a reliable Best .NET development company by your side.
0 notes
Text
Hire .NET Developers: A Practical Guide to Machine Learning in .NET
Machine learning (ML) has become a transformative force in the realm of technology, allowing systems to learn and adapt from data without explicit programming. While traditionally associated with languages like Python and R, the .NET ecosystem has made significant strides in integrating machine learning capabilities, providing developers, including those you might want to hire .NET developers, with powerful tools for building intelligent applications. In this practical guide, we'll explore the landscape of machine learning in .NET, covering key libraries, frameworks, and practical examples to get you started on your machine learning journey. This is particularly relevant for businesses looking to expand their team and hire .NET developers with a skill set that extends to machine learning applications.
Understanding the Basics
Before delving into the specifics of machine learning in .NET, let's briefly touch upon the foundational concepts. Machine learning involves training models on data to make predictions or decisions without being explicitly programmed. The process typically includes data collection, model training, evaluation, and deployment.
ML.NET: The Machine Learning Library for .NET
At the heart of .NET's machine learning capabilities lies ML.NET, an open-source and cross-platform machine learning framework developed by Microsoft. ML.NET is not only a powerful tool for incorporating machine learning into applications but also a valuable asset when seeking to hire .NET developers for your projects. This framework enables developers to seamlessly integrate machine learning functionalities into their .NET applications, making it an attractive skill set for businesses looking to expand their teams and hire .NET developers with expertise in diverse ML tasks, including classification, regression, clustering, and anomaly detection. Embracing ML.NET not only enhances your application's intelligence but also opens up opportunities to bring in skilled professionals as you embark on your journey to hire .NET developers with a flair for machine learning.
Installation and Setup
To get started with ML.NET, you need to install the ML.NET NuGet package. Once installed, you can leverage the capabilities of this powerful machine learning framework within your .NET projects. Whether you are working with the traditional .NET Framework or the more recent .NET Core/5/6 applications, ML.NET ensures compatibility and flexibility. This versatility makes it an ideal choice for projects handled by a skilled Best .NET development company looking to integrate machine learning capabilities. If you are planning to incorporate advanced machine learning features into your applications and considering outsourcing, partnering with a reputable best .NET development company can provide the expertise needed to navigate the intricacies of ML.NET seamlessly. The support for both traditional and modern .NET platforms further extends the possibilities when deciding to collaborate with a proficient Best .NET development company for your software projects.
bash
dotnet add package Microsoft.ML
Building Your First Model
Let's dive into a simple example to understand how to build a basic ML.NET model. Consider a scenario where you want to predict housing prices based on features like square footage, number of bedrooms, and location. ML.NET uses a pipeline-based approach, making it intuitive for developers.
csharp
// Define a class to hold data
public class HouseData
{
public float Size { get; set; }
public int Bedrooms { get; set; }
public float Price { get; set; }
}
// Create an MLContext
var context = new MLContext();
// Load the data
var data = context.Data.LoadFromTextFile<HouseData>("path/to/your/data.csv", separatorChar: ',');
// Define the pipeline
var pipeline = context.Transforms.Conversion.MapValueToKey("Label", "Price")
.Append(context.Transforms.Concatenate("Features", "Size", "Bedrooms"))
.Append(context.Transforms.NormalizeMinMax("Features"))
.Append(context.Transforms.Conversion.MapKeyToValue("Price"));
// Train the model
var model = pipeline.Fit(data);
This simple example demonstrates loading data, defining features, and training a model using ML.NET's pipeline.
Integration with TensorFlow and ONNX
While ML.NET provides a broad set of capabilities, it also acknowledges the diversity of the machine learning landscape. Through TensorFlow and ONNX (Open Neural Network Exchange) integration, developers can leverage pre-trained models from popular frameworks seamlessly.
TensorFlow Integration
ML.NET's TensorFlow integration enables the use of TensorFlow models directly within .NET applications. This is particularly useful when you have a pre-trained TensorFlow model and want to incorporate it into your .NET project for tasks such as image recognition or natural language processing.
ONNX Support
ONNX is an open format for representing deep learning models. ML.NET's support for ONNX allows you to use models created in other frameworks like PyTorch or scikit-learn within your .NET applications, promoting interoperability across the machine learning ecosystem.
Model Evaluation and Metrics
Once you've trained your machine learning model, it's crucial to evaluate its performance. ML.NET provides various metrics for classification, regression, and clustering tasks, allowing you to assess the accuracy and effectiveness of your models. For businesses aiming to streamline this process and ensure optimal performance, it becomes imperative to consider the expertise of skilled professionals. This is where the role of experienced .NET developers comes into play.
When you hire .NET developers with proficiency in machine learning and ML.NET, you gain a strategic advantage in model evaluation and fine-tuning. Seasoned .NET developers possess the knowledge to interpret these metrics effectively, making informed decisions to enhance model accuracy and overall performance. Their expertise extends beyond just coding; they contribute significantly to the iterative process of refining machine learning models for optimal results.
Therefore, when evaluating the performance of your machine learning models in a .NET environment, considering the insights and contributions of expert .NET developers becomes a valuable asset. Their skill set ensures that your models not only meet performance expectations but also pave the way for continuous improvement. If you're looking to elevate your machine learning endeavors within the .NET ecosystem, don't hesitate to explore the option to hire .NET developers with a strong foundation in both development and machine learning evaluation.
csharp
var predictions = model.Transform(data);
var metrics = context.Regression.Evaluate(predictions);
Console.WriteLine($"R-Squared: {metrics.RSquared}");
Console.WriteLine($"Mean Absolute Error: {metrics.MeanAbsoluteError}");
These metrics provide insights into how well your model is performing on the given data.
Deployment Options
After successfully training and evaluating your model, the next step is deployment. ML.NET supports various deployment options, including integration with Azure Machine Learning for scalable and cloud-based solutions.
Conclusion
In this practical guide, we've scratched the surface of machine learning in .NET using the ML.NET framework. From understanding the basics to building and evaluating models, the .NET ecosystem offers a robust set of tools for developers venturing into the exciting field of machine learning. Whether you're working on predictive analytics, image recognition, or natural language processing, exploring the integration of machine learning in .NET opens up new possibilities for creating intelligent and adaptive applications.
Remember, the best way to master machine learning in .NET is through hands-on experience. So, if you're looking to expedite your journey into the world of machine learning and seeking expert guidance, consider partnering with a skilled Best .NET development company. Collaborating with a proficient Best .NET development company not only provides access to seasoned professionals but also ensures that your projects involving machine learning integration are executed with precision and expertise. So, roll up your sleeves, dive into the code, and let your journey into the world of machine learning with .NET begin with the support of a reliable Best .NET development company by your side.
0 notes
Text
Top 14 Power-packed C# Interview Questions and Answers 2023
Prepare for your programming interview with our comprehensive C# interview questions and answers collection. Boost confidence and master C# concepts. Start learning now! ( oops interview questions in c#)
Top 14 C# Inquiries Questions Answers 2023
Presentation
Is it true that you are getting ready for a C# interview and having an apprehensive outlook on it? Simply relax; we take care of you! Our far reaching guide on "C# Inquiries Questions and Replies" is here to outfit you with the information and certainty you really want to handle the meeting like an ace. Whether you have 5 years of involvement or 10 years, this article is custom fitted to take care of your requirements and assist you with standing apart among different up-and-comers.
C# is a strong and generally utilized programming language, particularly in the domain of Microsoft improvement. It fills in as the foundation of numerous applications, including web, work area, versatile, and cloud-based arrangements. As you plan for your C# interview, it's fundamental to have areas of strength for an of the language's essentials, high level ideas, and best practices.
In this aide, we will cover an extensive variety of C# inquiries questions, beginning from the nuts and bolts and progressively advancing to further developed subjects. You'll find questions connected with C# grammar, information types, control structures, object-situated programming (OOP) standards, LINQ, special case taking care of, multithreading, and that's only the tip of the iceberg. Each question is cautiously organized to mirror the kinds of difficulties you could experience during your meeting.
To make the opportunity for growth connecting with and successful, we've included itemized clarifications and model code for each inquiry. This will help you comprehend the ideas as well as gain reasonable experiences into executing arrangements. Also, we'll give tips and deceives to advancing your C# code and dealing with normal entanglements.
Furthermore, we comprehend that meetings can be unpleasant, and being totally ready goes past specialized information. We'll offer direction on the most proficient method to move toward social inquiries, share your previous encounters, and show your critical thinking abilities really. An effective meeting isn't just about offering the right responses yet in addition exhibiting your excitement, flexibility, and capacity to work in a group.
Find the best 5 vehicle run cam models for improved street wellbeing and recording abilities.
Whether you're talking with for a lesser engineer position or a senior-level job, our aide has something for everybody. We've incorporated a different scope of inquiries to challenge you at different levels and guarantee you're completely ready for any situation.
Keep in mind, interviews are a trial of what you know as well as an open door to exhibit your energy for programming and your eagerness to learn and develop. Be certain, remain mentally collected, and let your insight and abilities sparkle.
Thus, assuming you're prepared to succeed in your C# interview and land that fantasy job, how about we jump into our exhaustive aide. With our assistance, you'll be completely ready to pro the meeting and make the following stride in your thrilling C# advancement venture. Allow the figuring out how to start!
See more info: - https://futuretechhub.in/csharp-interview-question-answers/
0 notes
Note
Hiya! Just found your blog, and first of all it’s awesome that you’re learning so many things!! and there’s so much progress good job :000
My best friend started a course on c# coding but they’ve been feeling so stressed out that they have been avoiding it for the longest time, that i decided that i’ll learn as well and help them cause i want them to succeed, understand and be confident!!
But uhhhh… obviously i don’t have access to the course that they are doing, and they don’t have notes for me, cause they haven’t been doing it….
Can you please point me to good starting out c# resources? And uhh probably a question for the future, would it be okay if i would pop in here from time to time with questions about code? thank you in advance for answering and please have a wonderful day, don’t forget to take breaks and drink water!
Hallo Hallo! ≧◉◡◉≦
I’m sorry your friend is struggling with C# right now, C# is literally the hardest programming language I’ve tried yet so I understand the feeling. I just submitted a C# project that was due on the 18th of April… I just couldn’t understand Abstract classes and Interface and it took me a month to understand them. Sometimes I just need a break from C# altogether! But props to you for wanting to learn C# and help them, especially since you’re going the self-taught route!
So, C# resources! As I am still learning (only 6 months into my apprenticeship) my advice is like amateur/junior level! But I’ll try my best! This is my advice and I know some more experienced c# programmers might be like “Erm, no?” but hey ho I’m trying my best!
Microsoft C# Documentation
Use this like your religious/spiritual book. It’s hella confusing at first but always just refer back to this, especially good practises and error codes you don’t understand. I recommend going over the ‘Learn to program in C#’, ‘C# fundamentals’ and ‘Key Concepts’. Just skim read them, watch the videos, do the tutorials, save them on your computer to look back, make notes and more. Read read read until you understand. And if you can’t, there’s Youtube that can visually show you how.
The way my teacher taught C#
This is the order he taught us and I am very confident up to Topic 9. I’m still going over notes from there on and doing the homework. If you have any questions from topics 1 to 8, I’d be happy to help! WinForms and Databases (C# x SQL) were included because I did those before my C# learning but I can help with those too!
The basics - installing Visual Studio, first console app, first WinForm
Methods
Intro to Conditionals
More on Conditionals
Loops
Arrays
Object-Oriented Programming - data types, classes, objects, the fours OOP concepts with C#
OOP - fields and methods
Enums and Strings
Collections and Generics
Working with files
The meaning of ‘static’
Exceptions
Intro to Inheritance
Inheritance towards Polymorphism
Abstract classes and Interfaces (where I had struggles with recently ahaha)
Generic Interfaces
Introduction to Testing
Solid principles and Design patterns
C# Learning Websites
C# Tutorial by Demo2s
C# Tutorials by BrainBell
C# programming by TutorialsTeacher
Learn c# Programming by Programiz
C# Tutorial for Beginners by Guru99
C# Tutorial by C#Station
C# by Learncs.org
C# / CSharp Tutorial by Java2s
Youtube Channels
FreeCodeCamp.org C# Section
Programming with Professor Sluiter
Academy Artan
ProgrammingGeek
ASPNET WEBFORM
Barry Solomon
Fox Learn
The C# Academy
Shaun Halverson
RJ Code Advance EN
Obviously, there are loads more but these are the ones I like the most. Some of them are like years old but still relevant in terms of the basic concepts of each topic. And some are more project-oriented.
Youtube Playlists
Beginning C# by Programming with Professor Sluiter
Programming in C# by mkaatr
C#.NET Tutorials by Programming with Mosh
C# Complete Tutorial From Beginner To Advance by FL Developers - 8 hours but please take your time, make notes and follow him, he's really good imo
C# Tutorials by Caleb Curry
C# Excerises/Homework/Projects
C# Sharp Programming Exercises, Practice, Solution by w3resource
Practise Exercises C# Sharp
C# by Exercism
250+ C# Basic: Exercises, Practice, Solution | C# programming examples and solutions by Tech Study
Visual C# exercises by WiseOwl
Online Books
C Sharp Programming Book (226 pages)
Introduction to C# (65 pages)
Other books on C#Corner
Discord
I would recommend joining a community for help and inspiration. I joined one on Discord called C# (LINK), they have like actual C# experts on there - Had one read my code and he said it looked great, I literally melted in my seat I was so happy XD
I hope this helps as a starter! And like you mentioned, you can dm or ask me any questions. And if you’re in need of homework for topics, I can give you similar homework tasks my tutor gave us / make some up for you, I don’t mind. BUT REMEMBER I am still like beginner/Junior (I would say more low-level Junior) with C# so if I’m like uhhhh, I’ll just ask my tutor/my colleagues at work and see if they can give feedback.
But yeah! This is all I can think of right now as help! Dm me if you are stuck on anything! Have a nice day! ᕙ(`▿´)ᕗ
#my asks#my resources#csharp programming#programming#coding#studyblr#comp sci#100 days of code#resources#programming resource
116 notes
·
View notes
Text
so you want to learn to code? ^w^ epic !! you can always take classes and whatnot, but you can also learn online >w<
if you’re interested in making a game, the first question is do you want to try and create it with a game maker, or with a programming language! game makers will be much easier for those who haven’t programmed, but doing it by yourself gives you much more control over every aspect of the game :}
if you’re looking at making a fairly typical game, or an rpg, or a text based game, and you don’t need many custom mechanics, it might be good to look into gamemakers ! but if you don’t have the money, or you’d like to step outside of the box, here’s where you can get started :D
big big huge biggest question :} what language would you like to learn! there are a ton of different languages, and they’re all useful for different things :D let me introduce you to a couple of common ones! (note: you can learn a language if you like, then move on to a game ide (which might help you understand the overall coding concepts more) or you can go straight to a game ide and learn whatever language it uses, which i think might be more difficult but if you’re only interested in making games, it should b fine!)
html+css+javascript: these are used in tandem for making responsive websites!
python: generally considered a good language for beginners, syntax is very different than java-like languages, tends to not be used for games but some like the sims 4 and doki doki literature club are made in it / use it!
java: the big guns... this can teach you the base for a lot of key programming concepts that are crucial in game making! i also find my knowledge of java to be very translatable to pretty much any coding problems i come across :D java was used to make minecraft, simcity, and more. although it’s certainly not the top choice for game devs, its very similar to the one that most people use ^_^
c++/c#: even though these are languages with different bases, i’m grouping them together because they’re both included in unity :3 these are the guys you want to get to know well if you’re learning games! the syntax is very very similar to java, and c++ is an object oriented language just like java ! the differences between the two come down to things like garbage collection and interpreters, which just means they’re going to feel the same to write in ^_^
Here are some resources for the different languages :}
html+css+js:
https://www.khanacademy.org/computing/computer-programming/html-css
https://www.khanacademy.org/computing/computer-programming/html-css-js
https://www.codecademy.com/learn/learn-html
python:
https://www.codecademy.com/learn/learn-python
https://www.learnpython.org/
java:
https://www.codecademy.com/learn/learn-java
https://www.learnjavaonline.org/
c++/c#:
https://www.codecademy.com/learn/learn-c-plus-plus
https://www.learncpp.com/
https://www.codecademy.com/learn/learn-c-sharp
https://dotnet.microsoft.com/learn/csharp
(you’ll notice that most of the places have the same names, codeacademy is a rlly great place to learn all of these languages ^u^)
another incredible resource is youtube! im not going to link videos because i personally haven’t used too many for learning these languages (i read books p much) but finding a tutorial that you vibe with is a really nice way to start, and there’s a lot of great free materials on there!
resources for learning unity:
https://learn.unity.com/
https://www.youtube.com/user/Brackeys
https://www.youtube.com/playlist?list=PLPV2KyIb3jR5QFsefuO2RlAgWEz6EvVi6
i’m not linking a lot of these because i’m just linking the ones that were the absolute most helpful ones to me, but hopefully these should at least get you started!
i wish y’all luck if you’re learning coding and game making :} it’s hard but its very rewarding! feel free to msg me here if you have any questions or just want to talk abt game stuff ^_^
#coding#unity#gamedev#d.txt#im mainly makin this for absolute beginners bc there's a chunk of people in the AF server who want to learn game making but don't know#where to start :}#so hopefully this helps !! i wish i could put more links but rn i have to actually go design stuff for my game lole
116 notes
·
View notes
Video
instagram
Go check out our websites Resources category on designmorphine.com/resources , new and updated resources added! - A curated collection of FREE intro to software courses made by amazing people and hand picked for quality by our team. There are so many free intro courses out there that there is no need to re-create them each time. So we search through the internet noise to find the best intro tutorials we ourselves recommend so you don’t have to waste time learning the wrong way, not all tutorials are equal and we consider these to be the best of the best! - Please support these talented educators by subscribing to their channels and viewing their content. - Think we missed something or have a great intro course you want to recommend for us to check out? Send us a direct message and let us know! We are specifically looking for the best of the best intro courses that must be a series, introduction level, and most importantly - FREE. . . . . #grasshopper3d #autodeskmaya #houdini #fusion360 #sidefxhoudini #autodeskmaya #design #unity #architecture #superarchitects #shapediver #csharp #ntopology #adobe #computationaldesign #python #parametricism #parametricarchitecture #cinema4d #desigmorphine #architecturestudent #rhino #unrealengine #processing #parametric #zbrush #blender #revit #dynamo #keyshot (at 𝓣𝓱𝒆 𝓤𝒏𝒊𝓿𝒆𝒓𝒔𝒆) https://www.instagram.com/p/CSPLZzcge6U/?utm_medium=tumblr
#grasshopper3d#autodeskmaya#houdini#fusion360#sidefxhoudini#design#unity#architecture#superarchitects#shapediver#csharp#ntopology#adobe#computationaldesign#python#parametricism#parametricarchitecture#cinema4d#desigmorphine#architecturestudent#rhino#unrealengine#processing#parametric#zbrush#blender#revit#dynamo#keyshot
2 notes
·
View notes
Photo

Clean Code Rules: 29. Use design patterns Design patterns are reusable code solutions to commonly occurring problems in software applications. They are not solutions to specific issues but templates for common problems in various contexts. You can reuse them in many different situations. In short, they’re a collection of best practices. Design patterns can help you write more readable code and avoid redundant and error-prone code. #software_development #programming #dotnet #csharp #dotnetdevelopment #webdevelopment #coding #workstation #workdesk #clean_code #uncle_bob #robert_c_martin #sagharmax (at Urmia) https://www.instagram.com/p/Cp2xm2JIUiD/?igshid=NGJjMDIxMWI=
#software_development#programming#dotnet#csharp#dotnetdevelopment#webdevelopment#coding#workstation#workdesk#clean_code#uncle_bob#robert_c_martin#sagharmax
0 notes
Text
.NET Core Platform Agnostic Tracing
While working on a project recently I recommended implementing tracing in some components using .NET Event Sources and ETW. The company were using .NET Core and mix of Windows and Linux operating systems. The architecture team were looking for a platform agnsotic solution. ETW can't work on Linux because it's built into the Windows Kernal and also the clue's in the name Event Tracing for Windows.
Setup
I investigated and immediately found out about LTTng which could do everything needed:
tracing event sources
real time tracing
filtering
I bashed together a .NET Core console application that would trace a message using an Event Source and quickly tested it on Windows using an ETW trace viewer tool.
Event Source
using System.Diagnostics.Tracing; namespace ConsoleApp1 { [EventSource(Name = "TestEventSource")] public class TestEventSource : EventSource { public static readonly TestEventSource Current = new TestEventSource(); private TestEventSource() : base() { } public static class Keywords { public const EventKeywords Messages = (EventKeywords)0x1L; } private const int MessageEventId = 1; [Event(MessageEventId, Level = EventLevel.Informational, Message = "{0}", Keywords = Keywords.Messages)] public void Message(string message) { if (this.IsEnabled()) { WriteEvent(MessageEventId, message); } } } }
Main Program
using System; namespace ConsoleApp1 { class Program { static void Main(string[] args) { Console.WriteLine("Running trace event source test app..."); TestEventSource.Current.Message("Hello World!"); TestEventSource2.Current.Message("World Hello!"); } } }
Then I created a Ubuntu.18.04-x64 server in Azure and transferred the application. To build the .NET Core application for Ubuntu I used this command:
dotnet publish -c release -r ubuntu.18.04-x64
To install LTTng I used the following terminal commands:
apt-get install lttng-tools
apt-get install lttng-modules-dkms
apt-get install liblttng-ust-dev
LTTng has great docs here.
Then I installed the .NET Core SDK following these instructions.
Tracing to file storage
Run the following terminal commands:
lttng create jimssession lttng enable-event --userspace --tracepoint DotNETRuntime:EventSource lttng start
In order for this to work I had to enable the DotNETRuntime environment variable COMPlus_EnableEventLog. There are two ways to do this:
1. With the command to run the .NET Core App
COMPlus_EnableEventLog=1 dotnet ./publish/ConsoleApp1.dll
2. Seperately in the terminal and then it stays set
export COMPlus_EnableEventLog=1
Then you can just run your .NET Core app without using the 'dotnet' command:
./publish/ConsoleApp1
To view your trace output I used a tool called Babeltrace. I think this was with the LTTng install so should already be available.
Run these commands in the terminal to view your trace output:
lttng stop Babeltrace lttng-traces/jimssession-20181124-183519
When you initialised the session you will have been notified of this trace output folder path. Your traces should be shown below after executing the Babeltrace command above.

Real-Time Tracing (live-tracing)
For real time tracing I had to use two terminal sessions seeing as I was using one to execute my console application but if you have an application already running on a Linux machine then you wouldn't need to do that.
Here's what I did:
In terminal 1:
lttng create jimssession --live
lttng enable-event --userspace --tracepoint DotNETRuntime:EventSource
In terminal 2:
babeltrace --input-format=lttng-live net://localhost/host/machineName/jimssession
In terminal 1:
lttng start
and execute the app:
./publish/ConsoleApp1

Here's the output:
There are great instructions for this by Pavel Makhov here and you can easily do remote tracing using the --set-url parmater.
Filtering
With ETW you can filter by event source and that's very useful for reducing noise when you're debugging. I was expecting that the enable-event command parameter --tracepoint would be the event source name and to be honest spent a lot of time scratching my head and wondering why nothing was being traced until I figured out the parameter value must be DotNETRuntime:EventSource. Obviously if it were the event source name then filtering would be easy because you would just enable-event for each source you wished to trace. Well it is easy anyway because there is another parameter on the enable-event command --filter. So to filter by event source I was able to do this:
lttng enable-event --userspace --tracepoint DotNETRuntime:EventSource --filter '(EventSourceName == "TestEventSource")'
The filter syntax is well document here.
Using NET Core ILogger
As ILogger is the preferred method for Logging in NET Core I had to investigate the possibility of using this for tracing also. Event Source tracing is supported in NET Core using ILogger through the EventSource provider but there are some pretty extreme limitations. The docs also say "The provider is cross-platform, but there are no event collection and display tools yet for Linux or macOS" - Not true in a way as I was at least able to collect some traces on Linux using LTTng.
For the default setup you can just use logging.AddEventSourceLogger() as documented here or in my case because I was using a console app I had to do this:
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace ILoggerEventSourceLogging { class ILoggerTestEventSource { private readonly ILogger _logger; public ILoggerTestEventSource(ILogger logger) { _logger = logger; } static void Main(string[] args) { var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); var serviceProvider = serviceCollection.BuildServiceProvider(); var program = serviceProvider.GetService(); program._logger.LogInformation("Hello World"); } private static void ConfigureServices(IServiceCollection services) { services.AddLogging(configure => configure.AddEventSourceLogger()) .Configure(options => options.MinLevel = LogLevel.Information) .AddTransient(); } } }
So I tested this first with my goto ETW trace viewer and I didn't see any output? So I decided seeing as the docs here suggest using the Microsoft PerfView utility (download the exe for here) then I would try that.
I did manage to view my trace output as promised however I wasn't overly satisfied because I'm not a big fan of the PerfView interface:

You can see above that ILogger outputs four traces for each single log statement in your code:
EventSourceMessage
FormattedMessage
Message
MessageJson
Not having any success with my goto ETW trace viewer tool I decided to see if LTTng would capture the events on Linux. It did and here's the output:

First, you can see the four ILogger traces, second there is an error on the 'EventSourceMessage' Exception in Command Processing for EventSource Microsoft-Extensions-Logging: Object reference not set to an instance of an object.
So this suggests to me that the NET Core default EventSource provider does not conform properly to the EventSource format rules.
So to make this work with my goto ETW trace viewer tool and error free with LTTng I had to use a custom provider with ILogger.
Here's what you need:
The logging provider classes I used can be found here:
https://github.com/aspnet/Extensions/tree/master/src/Logging/Logging.EventSource/src
Event Source Logger
using System; using System.Collections.Generic; using System.Diagnostics.Tracing; using System.IO; using System.Linq; using System.Threading; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace ILoggerEventSourceLogging { internal class EventSourceLogger : ILogger { private static int _activityIds; private readonly ILoggerEventSource _eventSource; private readonly int _factoryId; internal static readonly LogLevel LoggingDisabled = LogLevel.None + 1; public EventSourceLogger(string categoryName, int factoryId, ILoggerEventSource eventSource, EventSourceLogger next) { CategoryName = categoryName; // Default is to turn off logging Level = LoggingDisabled; _factoryId = factoryId; _eventSource = eventSource; Next = next; } public string CategoryName { get; } private LogLevel _level; public LogLevel Level { get { // need to check if the filter spec and internal event source level has changed and update the loggers level if it has _eventSource.ApplyFilterSpec(); return _level; } set { _level = value; } } // Loggers created by a single provider form a linked list public EventSourceLogger Next { get; } public bool IsEnabled(LogLevel logLevel) { return logLevel >= Level; } public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) { if (!IsEnabled(logLevel)) { return; } // See if they want the formatted message if (_eventSource.IsEnabled(EventLevel.Critical, _eventSource.FormattedMessageKeyword)) { var message = formatter(state, exception); _eventSource.FormattedMessage(logLevel, _factoryId, CategoryName, eventId.ToString(), message); } #if !NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT // See if they want the message as its component parts. if (_eventSource.IsEnabled(EventLevel.Critical, _eventSource.MessageKeyword)) { var exceptionInfo = GetExceptionInfo(exception); var arguments = GetProperties(state); _eventSource.ExceptionMessage(logLevel, _factoryId, CategoryName, eventId.ToString(), exceptionInfo, arguments); } #endif // See if they want the json message if (_eventSource.IsEnabled(EventLevel.Critical, _eventSource.JsonMessageKeyword)) { var exceptionJson = "{}"; if (exception != null) { var exceptionInfo = GetExceptionInfo(exception); var exceptionInfoData = new[] { new KeyValuePair("TypeName", exceptionInfo.TypeName), new KeyValuePair("Message", exceptionInfo.Message), new KeyValuePair("HResult", exceptionInfo.HResult.ToString()), new KeyValuePair("VerboseMessage", exceptionInfo.VerboseMessage), }; exceptionJson = ToJson(exceptionInfoData); } var arguments = GetProperties(state); _eventSource.MessageJson(logLevel, _factoryId, CategoryName, eventId.ToString(), exceptionJson, ToJson(arguments)); } } public IDisposable BeginScope(TState state) { if (!IsEnabled(LogLevel.Critical)) { return NoopDisposable.Instance; } var id = Interlocked.Increment(ref _activityIds); // If JsonMessage is on, use JSON format if (_eventSource.IsEnabled(EventLevel.Critical, _eventSource.JsonMessageKeyword)) { var arguments = GetProperties(state); _eventSource.ActivityJsonStart(id, _factoryId, CategoryName, ToJson(arguments)); return new ActivityScope(_eventSource, CategoryName, id, _factoryId, true); } else { #if !NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT var arguments = GetProperties(state); _eventSource.ActivityStart(id, _factoryId, CategoryName, arguments); #else _eventSource.ActivityStart(id, _factoryID, CategoryName); #endif return new ActivityScope(_eventSource, CategoryName, id, _factoryId, false); } } private class ActivityScope : IDisposable { private readonly string _categoryName; private readonly int _activityId; private readonly int _factoryId; private readonly bool _isJsonStop; private readonly ILoggerEventSource _eventSource; public ActivityScope(ILoggerEventSource eventSource, string categoryName, int activityId, int factoryId, bool isJsonStop) { _categoryName = categoryName; _activityId = activityId; _factoryId = factoryId; _isJsonStop = isJsonStop; _eventSource = eventSource; } public void Dispose() { if (_isJsonStop) { _eventSource.ActivityJsonStop(_activityId, _factoryId, _categoryName); } else { _eventSource.ActivityStop(_activityId, _factoryId, _categoryName); } } } private class NoopDisposable : IDisposable { public static readonly NoopDisposable Instance = new NoopDisposable(); public void Dispose() { } } private ExceptionInfo GetExceptionInfo(Exception exception) { var exceptionInfo = new ExceptionInfo(); if (exception != null) { exceptionInfo.TypeName = exception.GetType().FullName; exceptionInfo.Message = exception.Message; exceptionInfo.HResult = exception.HResult; exceptionInfo.VerboseMessage = exception.ToString(); } return exceptionInfo; } private IEnumerable> GetProperties(object state) { var arguments = new List>(); var asKeyValues = state as IEnumerable>; if (asKeyValues != null) { arguments.AddRange(from keyValue in asKeyValues where keyValue.Key != null select new KeyValuePair(keyValue.Key, keyValue.Value?.ToString())); } return arguments; } private string ToJson(IEnumerable> keyValues) { var sw = new StringWriter(); var writer = new JsonTextWriter(sw) { DateFormatString = "O" }; writer.WriteStartObject(); foreach (var keyValue in keyValues) { writer.WritePropertyName(keyValue.Key, true); writer.WriteValue(keyValue.Value); } writer.WriteEndObject(); return sw.ToString(); } } }
Event Source Logger Provider
using System.Diagnostics.Tracing; using Microsoft.Extensions.Logging; namespace ILoggerEventSourceLogging { public class EventSourceLoggerProvider : ILoggerProvider { // A small integer that uniquely identifies the LoggerFactory assoicated with this LoggingProvider. // Zero is illegal (it means we are uninitialized), and have to be added to the factory. private int _factoryId; private LogLevel _defaultLevel; private string _filterSpec; private EventSourceLogger _loggers; private readonly ILoggerEventSource _eventSource; public EventSourceLoggerProvider(ILoggerEventSource eventSource, EventSourceLoggerProvider next = null) { _eventSource = eventSource; Next = next; } public EventSourceLoggerProvider Next { get; } public Microsoft.Extensions.Logging.ILogger CreateLogger(string categoryName) { // need to check if the filter spec and internal event source level has changed and update the _defaultLevel if it has _eventSource.ApplyFilterSpec(); var newLogger = _loggers = new EventSourceLogger(categoryName, _factoryId, _eventSource, _loggers); newLogger.Level = ParseLevelSpecs(_filterSpec, _defaultLevel, newLogger.CategoryName); return newLogger; } public void Dispose() { // Turn off any logging SetFilterSpec(null); } // Sets the filtering for a particular logger provider public void SetFilterSpec(string filterSpec) { _filterSpec = filterSpec; _defaultLevel = GetDefaultLevel(); // Update the levels of all the loggers to match what the filter specification asks for. for (var logger = _loggers; logger != null; logger = logger.Next) { logger.Level = ParseLevelSpecs(filterSpec, _defaultLevel, logger.CategoryName); } if (_factoryId == 0) { // Compute an ID for the Factory. It is its position in the list (starting at 1, we reserve 0 to mean unstarted). _factoryId = 1; for (var cur = Next; cur != null; cur = cur.Next) { _factoryId++; } } } private LogLevel GetDefaultLevel() { var allMessageKeywords = _eventSource.MessageKeyword | _eventSource.FormattedMessageKeyword | _eventSource.JsonMessageKeyword; if (_eventSource.IsEnabled(EventLevel.Informational, allMessageKeywords)) { return _eventSource.IsEnabled(EventLevel.Verbose, allMessageKeywords) ? LogLevel.Debug : LogLevel.Information; } if (_eventSource.IsEnabled(EventLevel.Warning, allMessageKeywords)) { return LogLevel.Warning; } return _eventSource.IsEnabled(EventLevel.Error, allMessageKeywords) ? LogLevel.Error : LogLevel.Critical; } private LogLevel ParseLevelSpecs(string filterSpec, LogLevel defaultLevel, string loggerName) { if (filterSpec == null) { return EventSourceLogger.LoggingDisabled; // Null means disable. } if (filterSpec == string.Empty) { return defaultLevel; } var level = EventSourceLogger.LoggingDisabled; // If the logger does not match something, it is off. // See if logger.Name matches a _filterSpec pattern. var namePos = 0; var specPos = 0; for (; ; ) { if (namePos < loggerName.Length) { if (filterSpec.Length <= specPos) { break; } var specChar = filterSpec[specPos++]; var nameChar = loggerName[namePos++]; if (specChar == nameChar) { continue; } // We allow wildcards at the end. if (specChar == '*' && ParseLevel(defaultLevel, filterSpec, specPos, ref level)) { return level; } } else if (ParseLevel(defaultLevel, filterSpec, specPos, ref level)) { return level; } // Skip to the next spec in the ; separated list. specPos = filterSpec.IndexOf(';', specPos) + 1; if (specPos <= 0) // No ; done. { break; } namePos = 0; // Reset where we are searching in the name. } return level; } private bool ParseLevel(LogLevel defaultLevel, string spec, int specPos, ref LogLevel ret) { var endPos = spec.IndexOf(';', specPos); if (endPos < 0) { endPos = spec.Length; } if (specPos == endPos) { // No :Num spec means Debug ret = defaultLevel; return true; } if (spec[specPos++] != ':') { return false; } var levelStr = spec.Substring(specPos, endPos - specPos); switch (levelStr) { case "Trace": ret = LogLevel.Trace; break; case "Debug": ret = LogLevel.Debug; break; case "Information": ret = LogLevel.Information; break; case "Warning": ret = LogLevel.Warning; break; case "Error": ret = LogLevel.Error; break; case "Critical": ret = LogLevel.Critical; break; default: int level; if (!int.TryParse(levelStr, out level)) { return false; } if (!(LogLevel.Trace <= (LogLevel)level && (LogLevel)level <= LogLevel.None)) { return false; } ret = (LogLevel)level; break; } return true; } } }
Exception Info
namespace ILoggerEventSourceLogging { #if !NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT [System.Diagnostics.Tracing.EventData(Name = "ExceptionInfo")] #endif public class ExceptionInfo { public string TypeName { get; set; } public string Message { get; set; } public int HResult { get; set; } public string VerboseMessage { get; set; } // This is the ToString() of the Exception } }
Logger Event Source Interface
using System.Collections.Generic; using System.Diagnostics.Tracing; using Microsoft.Extensions.Logging; namespace ILoggerEventSourceLogging { public interface ILoggerEventSource { ILoggerProvider CreateLoggerProvider(); void FormattedMessage(LogLevel level, int factoryId, string loggerName, string eventId, string formattedMessage); void ExceptionMessage(LogLevel level, int factoryId, string loggerName, string eventId, ExceptionInfo exception, IEnumerable<KeyValuePair<string, string>> arguments); void ActivityStart(int id, int factoryId, string loggerName, IEnumerable> arguments); void ActivityStop(int id, int factoryId, string loggerName); void MessageJson(LogLevel level, int factoryId, string loggerName, string eventId, string exceptionJson, string argumentsJson); void ActivityJsonStart(int id, int factoryId, string loggerName, string argumentsJson); void ActivityJsonStop(int id, int factoryId, string loggerName); bool IsEnabled(EventLevel level, EventKeywords keywords); void ApplyFilterSpec(); EventKeywords MetaKeyword { get; } EventKeywords MessageKeyword { get; } EventKeywords FormattedMessageKeyword { get; } EventKeywords JsonMessageKeyword { get; } } }
Event Source
using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Text; using Microsoft.Extensions.Logging; namespace ILoggerEventSourceLogging { [EventSource(Name = "NetCoreLoggerEventSource")] public class NetCoreLoggerEventSource : EventSource, ILoggerEventSource { public static readonly NetCoreLoggerEventSource Current = new NetCoreLoggerEventSource(); #region Keywords public static class Keywords { // The four keywords below are part of the ASPNetCore logging implementation public const EventKeywords Meta = (EventKeywords)8; /// <summary> /// Turns on the 'Message' event when ILogger.Log() is called. It gives the information in a programatic (not formatted) way /// </summary> public const EventKeywords Message = (EventKeywords)16; /// <summary> /// Turns on the 'FormatMessage' event when ILogger.Log() is called. It gives the formatted string version of the information. /// </summary> public const EventKeywords FormattedMessage = (EventKeywords)32; /// <summary> /// Turns on the 'MessageJson' event when ILogger.Log() is called. It gives JSON representation of the Arguments. /// </summary> public const EventKeywords JsonMessage = (EventKeywords)64; } #endregion #region Code for implementing the ASPNet core logging ILoggerEventSource interface internal static readonly LogLevel LoggingDisabled = LogLevel.None + 1; private readonly object _providerLock = new object(); private string _filterSpec; private EventSourceLoggerProvider _loggingProviders; private bool _checkLevel; public ILoggerProvider CreateLoggerProvider() { lock (_providerLock) { var newLoggerProvider = new EventSourceLoggerProvider(this, _loggingProviders); _loggingProviders = newLoggerProvider; // If the EventSource has already been turned on. set the filters. if (_filterSpec != null) { newLoggerProvider.SetFilterSpec(_filterSpec); } return newLoggerProvider; } } public EventKeywords MetaKeyword => Keywords.Meta; public EventKeywords MessageKeyword => Keywords.Message; public EventKeywords FormattedMessageKeyword => Keywords.FormattedMessage; public EventKeywords JsonMessageKeyword => Keywords.JsonMessage; /// <summary> /// FormattedMessage() is called when ILogger.Log() is called. and the FormattedMessage keyword is active /// This only gives you the human reasable formatted message. /// </summary> #region FormattedMessage events public void FormattedMessage(LogLevel level, int factoryId, string loggerName, string eventId, string formattedMessage) { formattedMessage = formattedMessage ?? ""; switch (level) { case LogLevel.Critical: FormattedMessageCritical(factoryId, loggerName, eventId, formattedMessage); break; case LogLevel.Error: FormattedMessageError(factoryId, loggerName, eventId, formattedMessage); break; case LogLevel.Warning: FormattedMessageWarning(factoryId, loggerName, eventId, formattedMessage); break; case LogLevel.Information: FormattedMessageInformational(factoryId, loggerName, eventId, formattedMessage); break; case LogLevel.Debug: case LogLevel.Trace: FormattedMessageVerbose(factoryId, loggerName, eventId, formattedMessage); break; } } private const int FormattedMessageIdCritical = 111; private const int FormattedMessageIdError = 112; private const int FormattedMessageIdWarning = 113; private const int FormattedMessageIdInformational = 114; private const int FormattedMessageIdVerbose = 115; [Event(FormattedMessageIdCritical, Keywords = Keywords.FormattedMessage, Level = EventLevel.Critical, Message = "{3}")] private void FormattedMessageCritical(int factoryId, string loggerName, string eventId, string formattedMessage) { WriteEvent(FormattedMessageIdCritical, factoryId, loggerName, eventId, formattedMessage); } [Event(FormattedMessageIdError, Keywords = Keywords.FormattedMessage, Level = EventLevel.Error, Message = "{3}")] private void FormattedMessageError(int factoryId, string loggerName, string eventId, string formattedMessage) { WriteEvent(FormattedMessageIdError, factoryId, loggerName, eventId, formattedMessage); } [Event(FormattedMessageIdWarning, Keywords = Keywords.FormattedMessage, Level = EventLevel.Warning, Message = "{3}")] private void FormattedMessageWarning(int factoryId, string loggerName, string eventId, string formattedMessage) { WriteEvent(FormattedMessageIdWarning, factoryId, loggerName, eventId, formattedMessage); } [Event(FormattedMessageIdInformational, Keywords = Keywords.FormattedMessage, Level = EventLevel.Informational, Message = "{3}")] private void FormattedMessageInformational(int factoryId, string loggerName, string eventId, string formattedMessage) { WriteEvent(FormattedMessageIdInformational, factoryId, loggerName, eventId, formattedMessage); } [Event(FormattedMessageIdVerbose, Keywords = Keywords.FormattedMessage, Level = EventLevel.Verbose, Message = "{3}")] private void FormattedMessageVerbose(int factoryId, string loggerName, string eventId, string formattedMessage) { WriteEvent(FormattedMessageIdVerbose, factoryId, loggerName, eventId, formattedMessage); } #endregion FormattedMessage events #region ExceptionMessage events [NonEvent] public void ExceptionMessage(LogLevel level, int factoryId, string loggerName, string eventId, ExceptionInfo exception, IEnumerable> arguments) { var message = new StringBuilder(); foreach (var arg in arguments) message.Append($"{arg.Key} - {arg.Value}"); ExceptionMessage(level, factoryId, loggerName, eventId, exception.Message, message.ToString()); } public void ExceptionMessage(LogLevel level, int factoryId, string loggerName, string eventId, string exception, string message) { exception = exception ?? ""; message = message ?? ""; switch (level) { case LogLevel.Critical: ExceptionMessageCritical(factoryId, loggerName, eventId, exception, message); break; case LogLevel.Error: ExceptionMessageError(factoryId, loggerName, eventId, exception, message); break; case LogLevel.Warning: ExceptionMessageWarning(factoryId, loggerName, eventId, exception, message); break; case LogLevel.Information: ExceptionMessageInformational(factoryId, loggerName, eventId, exception, message); break; case LogLevel.Debug: case LogLevel.Trace: ExceptionMessageVerbose(factoryId, loggerName, eventId, exception, message); break; } } private const int ExceptionMessageIdCritical = 121; private const int ExceptionMessageIdError = 122; private const int ExceptionMessageIdWarning = 123; private const int ExceptionMessageIdInformational = 124; private const int ExceptionMessageIdVerbose = 125; [Event(ExceptionMessageIdCritical, Keywords = Keywords.Message, Level = EventLevel.Critical, Message = "{4}")] public void ExceptionMessageCritical(int factoryId, string loggerName, string eventId, string exception, string message) { WriteEvent(ExceptionMessageIdCritical, factoryId, loggerName, eventId, exception, message); } [Event(ExceptionMessageIdError, Keywords = Keywords.Message, Level = EventLevel.Error, Message = "{4}")] public void ExceptionMessageError(int factoryId, string loggerName, string eventId, string exception, string message) { WriteEvent(ExceptionMessageIdError, factoryId, loggerName, eventId, exception, message); } [Event(ExceptionMessageIdWarning, Keywords = Keywords.Message, Level = EventLevel.Warning, Message = "{4}")] public void ExceptionMessageWarning(int factoryId, string loggerName, string eventId, string exception, string message) { WriteEvent(ExceptionMessageIdWarning, factoryId, loggerName, eventId, exception, message); } [Event(ExceptionMessageIdInformational, Keywords = Keywords.Message, Level = EventLevel.Informational, Message = "{4}")] public void ExceptionMessageInformational(int factoryId, string loggerName, string eventId, string exception, string message) { WriteEvent(ExceptionMessageIdInformational, factoryId, loggerName, eventId, exception, message); } [Event(ExceptionMessageIdVerbose, Keywords = Keywords.Message, Level = EventLevel.Verbose, Message = "{4}")] public void ExceptionMessageVerbose(int factoryId, string loggerName, string eventId, string exception, string message) { WriteEvent(ExceptionMessageIdVerbose, factoryId, loggerName, eventId, exception, message); } #endregion ExceptionMessage events #region MessageJson events public void MessageJson(LogLevel level, int factoryId, string loggerName, string eventId, string exceptionJson, string argumentsJson) { exceptionJson = exceptionJson ?? ""; argumentsJson = argumentsJson ?? ""; switch (level) { case LogLevel.Critical: MessageJsonCritical(factoryId, loggerName, eventId, exceptionJson, argumentsJson); break; case LogLevel.Error: MessageJsonError(factoryId, loggerName, eventId, exceptionJson, argumentsJson); break; case LogLevel.Warning: MessageJsonWarning(factoryId, loggerName, eventId, exceptionJson, argumentsJson); break; case LogLevel.Information: MessageJsonInformational(factoryId, loggerName, eventId, exceptionJson, argumentsJson); break; case LogLevel.Debug: case LogLevel.Trace: MessageJsonVerbose(factoryId, loggerName, eventId, exceptionJson, argumentsJson); break; } } private const int MessageJsonIdCritical = 131; private const int MessageJsonIdError = 132; private const int MessageJsonIdWarning = 133; private const int MessageJsonIdInformational = 134; private const int MessageJsonIdVerbose = 135; [Event(MessageJsonIdCritical, Keywords = Keywords.JsonMessage, Level = EventLevel.Critical, Message = "{4}")] private void MessageJsonCritical(int factoryId, string loggerName, string eventId, string exceptionJson, string argumentsJson) { WriteEvent(MessageJsonIdCritical, factoryId, loggerName, eventId, exceptionJson, argumentsJson); } [Event(MessageJsonIdError, Keywords = Keywords.JsonMessage, Level = EventLevel.Error, Message = "{4}")] private void MessageJsonError(int factoryId, string loggerName, string eventId, string exceptionJson, string argumentsJson) { WriteEvent(MessageJsonIdError, factoryId, loggerName, eventId, exceptionJson, argumentsJson); } [Event(MessageJsonIdWarning, Keywords = Keywords.JsonMessage, Level = EventLevel.Warning, Message = "{4}")] private void MessageJsonWarning(int factoryId, string loggerName, string eventId, string exceptionJson, string argumentsJson) { WriteEvent(MessageJsonIdWarning, factoryId, loggerName, eventId, exceptionJson, argumentsJson); } [Event(MessageJsonIdInformational, Keywords = Keywords.JsonMessage, Level = EventLevel.Informational, Message = "{4}")] private void MessageJsonInformational(int factoryId, string loggerName, string eventId, string exceptionJson, string argumentsJson) { WriteEvent(MessageJsonIdInformational, factoryId, loggerName, eventId, exceptionJson, argumentsJson); } [Event(MessageJsonIdVerbose, Keywords = Keywords.JsonMessage, Level = EventLevel.Verbose, Message = "{4}")] private void MessageJsonVerbose(int factoryId, string loggerName, string eventId, string exceptionJson, string argumentsJson) { WriteEvent(MessageJsonIdVerbose, factoryId, loggerName, eventId, exceptionJson, argumentsJson); } #endregion MessageJson events [NonEvent] public void ActivityStart(int id, int factoryId, string loggerName, IEnumerable> arguments) { var message = new StringBuilder(); foreach (var arg in arguments) message.Append($"{arg.Key} - {arg.Value}"); ActivityStart(id, factoryId, loggerName, message.ToString()); } /// <summary> /// ActivityStart is called when ILogger.BeginScope() is called /// </summary> private const int ActivityStartId = 141; [Event(ActivityStartId, Keywords = Keywords.Message | Keywords.FormattedMessage, Level = EventLevel.Informational, ActivityOptions = EventActivityOptions.Recursive, Message = "{3}")] public void ActivityStart(int id, int factoryId, string loggerName, string message) { WriteEvent(ActivityStartId, id, factoryId, loggerName, message); } private const int ActivityStopId = 142; [Event(ActivityStopId, Keywords = Keywords.Message | Keywords.FormattedMessage, Level = EventLevel.Informational, Message = "")] public void ActivityStop(int id, int factoryId, string loggerName) { WriteEvent(ActivityStopId, id, factoryId, loggerName); } private const int ActivityJsonStartId = 143; [Event(ActivityJsonStartId, Keywords = Keywords.JsonMessage | Keywords.FormattedMessage, Level = EventLevel.Informational, ActivityOptions = EventActivityOptions.Recursive, Message = "{3}")] public void ActivityJsonStart(int id, int factoryId, string loggerName, string argumentsJson) { WriteEvent(ActivityJsonStartId, id, factoryId, loggerName, argumentsJson); } private const int ActivityJsonStopId = 144; [Event(ActivityJsonStopId, Keywords = Keywords.JsonMessage | Keywords.FormattedMessage, Level = EventLevel.Informational, Message = "")] public void ActivityJsonStop(int id, int factoryId, string loggerName) { WriteEvent(ActivityJsonStopId, id, factoryId, loggerName); } protected override void OnEventCommand(EventCommandEventArgs command) { lock (_providerLock) { if (command.Command == EventCommand.Update || command.Command == EventCommand.Enable) { string filterSpec; if (!command.Arguments.TryGetValue("FilterSpecs", out filterSpec)) { filterSpec = string.Empty; // This means turn on everything. } SetFilterSpec(filterSpec); } else if (command.Command == EventCommand.Update || command.Command == EventCommand.Disable) { SetFilterSpec(null); // This means disable everything. } } } /// <summary> /// Set the filtering specifcation. null means turn off all loggers. Empty string is turn on all providers. /// </summary> /// [NonEvent] private void SetFilterSpec(string filterSpec) { _filterSpec = filterSpec; // In .NET 4.5.2 the internal EventSource level hasn't been correctly set // when this callback is invoked. To still have the logger behave correctly // in .NET 4.5.2 we delay checking the level until the logger is used the first // time after this callback. _checkLevel = true; } [NonEvent] public void ApplyFilterSpec() { lock (_providerLock) { if (_checkLevel) { for (var cur = _loggingProviders; cur != null; cur = cur.Next) { cur.SetFilterSpec(_filterSpec); } _checkLevel = false; } } } #endregion } }
Main Program
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace ILoggerEventSourceLogging { class Program { private readonly ILogger _logger; public Program(ILogger logger) { _logger = logger; } static void Main(string[] args) { var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); var serviceProvider = serviceCollection.BuildServiceProvider(); var program = serviceProvider.GetService(); program._logger.LogInformation("Hello World from Jim"); } private static void ConfigureServices(IServiceCollection services) { services.AddLogging(configure => configure.ClearProviders().AddProvider(NetCoreLoggerEventSource.Current.CreateLoggerProvider())) .Configure(options => options.MinLevel = LogLevel.Information) .AddTransient(); } } }
So using this custom log provider I had success and was able to view the traces in my usual ETW trace viewer tool and also on Linux there were now no errors in the output:

and no more errors on Linux with LTTng:

References
http://blogs.microsoft.co.il/sasha/2017/03/30/tracing-runtime-events-in-net-core-on-linux/
https://lttng.org/blog/2018/08/28/bringing-dotnet-perf-analysis-to-linux/
https://lttng.org/
https://lttng.org/docs/v2.10/#doc-lttng-live
https://lttng.org/docs/v2.10/#doc-ubuntu
https://lttng.org/man/1/lttng-enable-event/v2.10/
https://lttng.org/blog/2017/11/22/lttng-ust-blocking-mode/
https://pavelmakhov.com/2017/01/lttng-streaming
https://www.microsoft.com/net/download/linux-package-manager/ubuntu18-04/sdk-current
https://lttng.org/man/1/lttng-enable-event/v2.10/#doc-filter-syntax
http://ctpd.dorsal.polymtl.ca/system/files/TracingSummit2015-LTTngFilteringeBPF.pdf
https://blogs.msdn.microsoft.com/luisdem/2017/03/19/net-core-1-1-how-to-publish-a-self-contained-application
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.1#eventsource-provider
https://www.blinkingcaret.com/2018/02/14/net-core-console-logging/
https://codeblog.dotsandbrackets.com/profiling-net-core-app-linux/
1 note
·
View note
Text
Shellcode Injection Techniques A collection of C# shellcode injection techniques. All techniques...
Shellcode Injection Techniques A collection of C# shellcode injection techniques. All techniques use an AES encrypted meterpreter payload. https://github.com/plackyhacker/Shellcode-Injection-Techniques #inject #shellcode #csharp

GitHub - plackyhacker/Shellcode-Injection-Techniques: A collection of C# shellcode injection techniques. All techniques use an… - GitHub A collection of C# shellcode injection techniques. All techniques use an AES encrypted meterpreter payload. I will be building this project up as I learn, discover or develop more techniques. Some ...
0 notes
Text
A brief Introduction of C-Sharp

Definition by Microsoft - C# (pronounced as C-sharp) is a modern, multi-paradigm programming language that enables the developers or programmers to build variety of secure and robust applications that runs on the .NET framework.
To conclude, C# is type-safe Object-Oriented Programming language that is developed by Microsoft that runs on .NET Framework which allows programmer to built reusable components. The development of C# is led by Anders Hejlsberg and team. The latest version of C# is C# 7.0, which was released back in 2017 along with Visual Studio 2017.
As an object oriented language, C# supports the concepts of encapsulation, inheritance and polymorphism. C# supports generic methods and types, which provide increased type safety and performance, and iterators, which enable implementers of collection classes to define custom iteration.
C# is used to develop various robust and secure applications such as:
Ø Web Applications
Ø Windows Applications
Ø Distributive Applications
Ø Database Applications and the list goes on.
C# language is basically designed for CLI (Common Language Infrastructure). CLI consists of the executable code and runtime environment that allows the use of various high-level languages. C# is very simple and easy to learn with having a highly expressive syntax. The oops concepts of C# are particularly similar to Java language, developers who know C++ or Java languages are typically able to begin to work productively in C# within a very short time.
C# follows the high-level languages like Java and C++ with being an object-oriented language it has intense similarity with Java. C# have numerous programming features that makes it one of the best programming language in the world.
Some of the notable features of C# are listed as:
Ø Object oriented and modern programming language
Ø Simple and easy to learn
Ø Structured programming language
Ø Scalable and interoperable
Ø Type safe
Ø Component of .Net Framework
So, these are some important features of C# language that makes C# a major programming language across the developers.
References:
https://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29
https://www.javatpoint.com/c-sharp-tutorial
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide
1 note
·
View note
Text
Top 14 C# Interview Questions Answers 2023 - Crack Interview
Prepare for your programming interview with our comprehensive C# interview questions and answers collection. Boost confidence and master C# concepts. Start learning now!
Top 14 C# Inquiries Questions Answers 2023
Presentation

Is it safe to say that you are planning for a C# interview and having an apprehensive outlook on it? Just relax; we take care of you! Our far reaching guide on "C# Inquiries Questions and Replies" is here to furnish you with the information and certainty you really want to handle the meeting like a genius. Whether you have 5 years of involvement or 10 years, this article is customized to take care of your necessities and assist you with standing apart among different up-and-comers.
C# is a strong and broadly utilized programming language, particularly in the domain of Microsoft improvement. It fills in as the foundation of numerous applications, including web, work area, versatile, and cloud-based arrangements. As you plan for your C# interview, it's fundamental to have areas of strength for an of the language's essentials, high level ideas, and best practices.
In this aide, we will cover an extensive variety of C# inquiries questions, beginning from the nuts and bolts and slowly advancing to further developed subjects. You'll find questions connected with C# punctuation, information types, control structures, object-situated programming (OOP) standards, LINQ, special case taking care of, multithreading, and that's only the tip of the iceberg. Each question is cautiously arranged to mirror the sorts of difficulties you could experience during your meeting.
To make the opportunity for growth connecting with and successful, we've included point by point clarifications and model code for each inquiry. This will help you comprehend the ideas as well as gain viable bits of knowledge into carrying out arrangements. Additionally, we'll give tips and deceives to improving your C# code and dealing with normal traps. c# interview questions
Also, we comprehend that meetings can be distressing, and being totally ready goes past specialized information. We'll offer direction on the most proficient method to move toward social inquiries, share your previous encounters, and show your critical thinking abilities really. An effective meeting isn't just about offering the right responses yet in addition displaying your excitement, versatility, and capacity to work in a group.
Find the best 5 vehicle run cam models for improved street wellbeing and recording capacities.
Whether you're talking with for a lesser designer position or a senior-level job, our aide has something for everybody. We've incorporated a different scope of inquiries to challenge you at different levels and guarantee you're good to go for any situation.
Keep in mind, interviews are a trial of what you know as well as an open door to grandstand your energy for programming and your readiness to learn and develop. Be sure, keep even headed, and let your insight and abilities sparkle.
In this way, assuming you're prepared to succeed in your C# interview and land that fantasy job, we should jump into our thorough aide. With our assistance, you'll be completely ready to pro the meeting and make the following stride in your astonishing C# improvement venture. Allow the figuring out how to start!
See More Info :- https://futuretechhub.in/csharp-interview-question-answers/
0 notes