[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

C#

93K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

Share tech news, updates, or what's on your mind.

Sign up to Post

Google Elevation API
The article's main focus is , to create a C# console application using Google's Elevation API. For more detailed information about this topic, use the attached links.
0
Learn Ruby Fundamentals
LVL 12
Learn Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

GEOCODING / REVERSE GEOCODING
The article's main focus is , to create the application using Google's GeoCoding/Reverse Geocoding. This article will teach you what GeoCoding and Reverse Geocoding is and how to write a simple C# console application. I also added some links, for more detailed information for this topic.
1
How many times have you tried using Office InterOp to manage various custom properties? If you have ever tried it then you will see the article image very appropriate. After spending hours trying to solve a question I finally gave up on Office InterOp and took an easier way out - OpenXML SDK.
0
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would attempt to address those here.
0
High user turnover can cause old/redundant user data to consume valuable space. UserResourceCleanup was developed to address this by automatically deleting user folders when the user account is deleted.
7
LVL 107

Expert Comment

by:John
Comment Utility
Interesting article. At my main client, we are not currently seeing high turnover (which is a good thing), but I have made a note and when there is an opportunity, we will try it out.

Thank you.
1
LVL 24

Expert Comment

by:Alan
Comment Utility
Thumbs up working now - thanks!

Alan.
1
In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
0
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
5
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
5
Code Performance
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
3
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a few months or a few weeks to get market trend inform.
0
Learn SQL Server Core 2016
LVL 12
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

DelegatesInC#
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that understanding with Experts-Exchange users.
2
LVL 11

Author Comment

by:ROMA CHAUHAN
Comment Utility
Hi St. Jimbo,

Thanks for your valuable inputs.

As this is my very first article so I was not aware of all these points. I have submitted my article with the specified modifications.  Please review it again.


Thanks,
Roma
0
LVL 75

Expert Comment

by:käµfm³d 👽
Comment Utility
Any method which matches the above delegate type can be assigned to this MyTestDelegate delegate.
What do you mean by "matches"?

To call those methods through delegate, we have to use Invloke() method of that delegate.
You can also just invoke the delegate like a function using parentheses, which if memory serves is just syntactic sugar for Invoke:

objMyTestDel(9);
 
objMyTestDel(15);

Asynchronous execution of method through delegate
Don't forget about the async/await functionality of .NET!
0
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
3
LVL 67

Expert Comment

by:Jim Horn
Comment Utility
Very well written, and I can see how this can be very useful.  Voted Yes.
0
LVL 111

Expert Comment

by:Ray Paseur
Comment Utility
0
Entity Framework 6
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
2

Expert Comment

by:Budheshwar Tiwari
Comment Utility
HI Alexandre,

i have use the second tricks of you mention this article but the error is bind the

==>  Invalid attempt to read when no data is present.
can you please help this issue.
**********The Store Procedure result is ******

SQL query Window**********These are Model ************

  public class UserDashboard
    {
        public List<UserMenuItem> DealOfTheDay { get; set; }
        public List<UserMenuItem> UserMenuList { get; set; }
        public List<MenuItemImage> MenuImageGallery { get; set; }
        public int TotalCartCount { get; set; }
    }
    public class UserMenuItem
    {
        public long ItemId { get; set; }
        public string ItemCode { get; set; }
        public string ItemName { get; set; }
        public decimal OutletPrice { get; set; }
        public decimal Calorie { get; set; }
        public string Discription { get; set; }
        public string UnitName { get; set; }
        public string ImageTitle { get; set; }
        public bool isFavorite { get; set; }
    }
    public class MenuItemImage
    {
        public int ImageID { get; set; }
        public long ItemId { get; set; }
        public string ImageTitle { get; set; }
    }
 ************* This is the function of code first multiple select Statement*************
        public UserDashboard GetAllUserDashboardData(long UserId, byte WalletType = 1)
        {
            UserDashboard result = new UserDashboard();
            var command = _Context.Database.Connection.CreateCommand();
            command.CommandText = "[dbo].[APIUserDashBoardData]";
            command.CommandType = CommandType.StoredProcedure;
            var userid = new SqlParameter("@UserId", UserId);
            var to = new SqlParameter("@WalletType", WalletType);
            command.Parameters.Add(userid);
            command.Parameters.Add(to);
            try
            {
                _Context.Database.Connection.Open();
                // Run the sproc  
                var reader = command.ExecuteReader();
                #region First Method to bind the entity by ef
                //// Read Blogs from the first result set
                //var DealOfTheDayList = ((IObjectContextAdapter)_Context)
                //    .ObjectContext
                //    .Translate<UserMenuItem>(reader, "Result1", MergeOption.AppendOnly);


                //foreach (var item in DealOfTheDayList)
                //{
                //    result.DealOfTheDay.Add(
                //        new UserMenuItem()
                //        {
                //            ItemId = item.ItemId,
                //            ItemCode = item.ItemCode,
                //            ItemName = item.ItemName,
                //            OutletPrice = item.OutletPrice,
                //            Calorie = item.Calorie,
                //            Discription = item.Discription,
                //            UnitName = item.UnitName,
                //            ImageTitle = item.ImageTitle,
                //            isFavorite = item.isFavorite,
                //        });
                //}
                //// Move to second result set and read Posts
                //reader.NextResult();
                //var MenuImageGalleryList = ((IObjectContextAdapter)_Context)
                //    .ObjectContext
                //    .Translate<MenuItemImage>(reader, "Result2", MergeOption.AppendOnly);


                //foreach (var item in MenuImageGalleryList)
                //{
                //    result.MenuImageGallery.Add(
                //        new MenuItemImage()
                //        {
                //            ImageID = item.ImageID,
                //            ImageTitle = item.ImageTitle,
                //            ItemId = item.ItemId,

                //        });
                //}

                //// Move to third result set and read Posts
                //reader.NextResult();
                //var UserMenuList = ((IObjectContextAdapter)_Context)
                //    .ObjectContext
                //    .Translate<UserMenuItem>(reader, "Result3", MergeOption.AppendOnly);


                //foreach (var item in UserMenuList)
                //{
                //    result.UserMenuList.Add(
                //        new UserMenuItem()
                //        {
                //            ItemId = item.ItemId,
                //            ItemCode = item.ItemCode,
                //            ItemName = item.ItemName,
                //            OutletPrice = item.OutletPrice,
                //            Calorie = item.Calorie,
                //            Discription = item.Discription,
                //            UnitName = item.UnitName,
                //            ImageTitle = item.ImageTitle,
                //            isFavorite = item.isFavorite,
                //        });
                //}

                #endregion
                #region Second Method to bind the entity by ef
                // Read Blogs from the first result set
                while (reader.Read())
                    {
                        result.DealOfTheDay.Add(
                            new UserMenuItem()
                            {
                                ItemId = reader.GetInt64(0),
                                ItemCode = reader.GetString(1),
                                ItemName = reader.GetString(2),
                                OutletPrice = reader.GetDecimal(3),
                                Calorie = reader.GetDecimal(4),
                                Discription = reader.GetString(5),
                                UnitName = reader.GetString(6),
                                ImageTitle = reader.GetString(7),
                                isFavorite = reader.GetBoolean(8),
                            });
                    }
                    //// Move to Second result set and read Posts
                    reader.NextResult();
                    while (reader.Read())
                    {
                        result.MenuImageGallery.Add(
                            new MenuItemImage()
                            {
                                ImageID = reader.GetInt32(0),
                                ItemId = reader.GetInt64(1),
                                ImageTitle = reader.GetString(2)
                            });
                    }
                    //// Move to third result set and read Posts
                    reader.NextResult();
                    while (reader.Read())
                    {
                        result.UserMenuList.Add(
                            new UserMenuItem()
                            {
                                ItemId = reader.GetInt64(0),
                                ItemCode = reader.GetString(1),
                                ItemName = reader.GetString(2),
                                OutletPrice = reader.GetDecimal(3),
                                Calorie = reader.GetDecimal(4),
                                Discription = reader.GetString(5),
                                UnitName = reader.GetString(6),
                                ImageTitle = reader.GetString(7),
                                isFavorite = reader.GetBoolean(8),
                            });
                    }
                    reader.NextResult();
                    while (reader.Read())
                    {
                        result.TotalCartCount = reader.GetInt32(0);
                    }
                    #endregion
               
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            finally
            {
                _Context.Database.Connection.Close();
            }
            return result;
        }

*********For more detail see the file attachments********************
Thanks
VS2017.png
0
Exception Handling is in the core of any application that is able to dignify its name.
In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
2
Project templates provide the class structure and definition of service contracts, data contracts and other important features in 
Visual Studio for Windows Communication Foundation
. Using these predefined template helps you to write a service with minimal code interaction and it will lead you to build more advanced services for your projects.

There are four different types of templates present in Visual Studio. The first two are the most commonly used to build, test and deploy SOA architectural applications.
 
1. WCF Service Library:
The WCF Service Library project (C#) consists of three files; IService1.cs, Service1.cs and App.config. The WCF Service Library project (VB.Net) is consists of three files; IService1.vb, Service1.vb and App.config.

This type of project is suitable when we are focused on building the services first and deployment later.
  • IService File: This is the interface where the WCF service attributes are applied. In this file you place the definitions of data contract methods/operations.
  • Service File: This file is inherited from IService interface file and includes the implementations of defined interface's data contract methods/operations. 
  • Application Configuration File: In this file, you place the definitions of secure HTTP binding, endpoints of services and other important features.

2. WCF Service Application:
The WCF…
0
You can find plenty of algorithms on the Internet that provide the Encryption - Decryption functionality. One of them is the AES algorithm. AES stands for "Advanced Encryption Standard".

The Advanced Encryption Standard was established by US National Institute of Standards and Technology in 2001. It was based; on the work of two Belgian cryptographers, Joan Daemen and Vincent Rijmen, who submitted the proposal to NIST during the selection process.

In the AES algorithm, there is a terminology we use called 'Cipher Mode'. There are different types Cipher Modes present in the algorithm. Based on your specific needs and requirements you can select the Cipher Modes. Let's have a look at what these are and how they differentiate from other cipher modes.

1. Electronic Code Book Mode: This mode doesn't require any feedback to be applied. You pass the plain text/data using this and and get the resulted Cipher data from it directly. The main disadvantage is that this mode will return the same cipher data on passing the same type of plain text in loop; if you pass 'Hello, World!' three times in this mode then it will return same cipher data in each iteration. That is why this mode is considered as 'Vulnerable' and not recommended for use.

2. Cipher Block Chaining Mode: This mode is required to add the feeback to modify the pre-encrypted data; with the feedback it will make each cipher data…
1
Mulithreading is a wonderful concept but it is one of the most complex way to achieve a task. Microsoft had provided probably the most efficient way to handle this problem by using async calls and thread pool. This provides an easy way to handle more than one task in an efficient way. But the biggest problem is thread creation and disposal of thread in this programming scenario. A common problem we are facing with UI programming is we are executing a task which takes a long time.

And if we are trying to do the same in Main Thread of application it freezes the UI until the completion of job. For example in the given program we are trying to run infinite loop and trying the display the count on textbox

 
using System;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        private TextBox textBox1;
        private Button btnStart;
    
        public Form1()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.btnStart = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // btnStart
            // 
            this.btnStart.Location = new System.Drawing.Point(134, 27);
            this.btnStart.Name = "btnStart";
            this.btnStart.Size = new System.Drawing.Size(75, 23);
            this.btnStart.TabIndex = 0;
       

Open in new window

0
Hi,

There are a lot of written methos of getting the difference between two dates, but I couldn't find the one I needed. I need to have a real difference like 3.75 months between the two dates.

Not every month has the same amount of days and the February is also an issue here. So I made myself a method doing this:

/// <summary>
/// Get months difference between two dates
/// </summary>
/// <param name="from">from date</param>
/// <param name="to">to date</param>
/// <returns>months (double) between </returns>
internal static double GetMonths(DateTime from, DateTime to)
{
	/// |-------X----|---------------|---------------|--X-----------|
	///         ^                                       ^
	///       from                                     to

	//change the dates if to is before from
	if (to.Ticks < from.Ticks)
	{
		DateTime temp = from;
		from = to;
		to = temp;
	}

	/// Gets the day percentage of the months = 0...1
	///
	/// 0            1                               0              1
	/// |-------X----|---------------|---------------|--X-----------|
	/// ^^^^^^^^^                                    ^^^^
	/// percFrom                                    percTo
	double percFrom = (double)from.Day / DateTime.DaysInMonth(from.Year, from.Month);
	double percTo = (double)to.Day / DateTime.DaysInMonth(to.Year, to.Month);

	/// get the amount of months between the two dates based on day one
	/// 
	/// |-------X----|---------------|---------------|--X-----------|
	

Open in new window

3
LVL 3

Author Comment

by:TGB01
Comment Utility
Hi mahmuod,

I know, but using this you get the real difference between two dates, like the days between the two dates (Double). In the TimeSpan, there is no Month property.

And in my case, the method is using one month as 100%, so every month can have different amount of days. So the same amount of days between two dates can have multiple results depending on the choosen dates.
0
LVL 1

Expert Comment

by:SimonPrice3376
Comment Utility
because of the complexity of the question, have you mapped out the sum on paper?  

if you can get the sum right using proper math, you should then be able to recreate the sum in a method \ function and return the value accordingly.
0
Sometimes when developing windows forms application, it becomes an important part of application design to persist the state of windows form after it is closed.

One such example that comes to my mind is an application called “Sticky Notes”.

Here the user is expected to open a notepad which she can re-size as and when required, can write few notes on it and then close this form. The notes are to be saved in a persistent storage like Database or XML.

Next time when the user opens that sticky note, it should open in the same size and display the notes that were written by the user last time.

As far as persistence of the notes to Database and/or XML file is concerned, I know there are many ways to do it. This article however deals with the second part of the problem, i.e. persistence of the form state in the application.

Some people might argue that if we can save note’s data in DB/XML we can also save form’s State. But, i personally feel that since form’s state is the data related to user interface, so it should be persisted somewhere in the application.

So let’s begin this tutorial by understanding the problem statement first:-

The Problem Statement

During the flow of an application, a windows form is opened. The User the re-sizes the form, make some other activity with the form and closes the form. Next time when the user opens this same form again, the size of the form should be same as when the form was closed.

Solution

Looking at …
4
LVL 8

Expert Comment

by:TheMozz
Comment Utility
Great article! I especially appreciate the comment about separating the application data from the UI specific data. It is easy to forget the difference when working on an app that has to be done "Right Now" (not that things are ever done that way..).
0
LVL 16

Expert Comment

by:Easwaran Paramasivam
Comment Utility
Excellent Article!!
0
OWASP: Forgery and Phishing
LVL 12
OWASP: Forgery and Phishing

Learn the techniques to avoid forgery and phishing attacks and the types of attacks an application or network may face.

This article is for Object-Oriented Programming (OOP) beginners.

An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Interface member. In C# multiple inheritance is achieved with the help of Interfaces.

Therefore, if the Development Team is large or 3rd-party vendors are involved, then it may possible that two team members may end up creating two different Interfaces with the same method name. Consequently, as a developer you may have to implement both these Interfaces in one Class.

Scenario: So let’s assume that –

You have two different Interfaces let’s say ICustomer and IVendor. Both the Interfaces have a method with same name let's say GetData().

GetData() from ICustomer would return the list of customer names while GetData() from IVendor would return the list of vendor names. In the data access layer, a single class CompanyDAL implements both these Interfaces.

See attached Code Snippet for Interface definitions –
using System.Collections.Generic;

namespace ExplicitInterfacesSite
{
    // Simple interface for Vendor class
    public interface IVendor
    {
        // Return the list of vendor names
        List<string> GetData();
    }

    // Simple interface for customer class
    public interface ICustomer
    {
        // Return the list of  customer names.
        // This function name is conflicting with 

Open in new window

3
Introduction
Hi all and welcome to my first article on Experts Exchange.
A while ago, someone asked me if i could do some tutorials on object oriented programming.

I decided to do them on C#. Now you may ask me, why's that?
Well, one of the reasons was that i have more C# than C/C++ knowledge.
Another one is that C# is becoming more and more a very important language, and forces you to think object oriented, wich is a style of programming were lots of people who are used to traditional techniques have trouble understanding with.
And last but not least, when you combine C# with the powerfull Microsoft XNA Framework it becomes fairly easy to create games that work on both PC and Xbox and even on Windows Phone 7.

Also, i decided to write them, instead of making video's.
Video's are handy, but not that functional when it comes to programming (imo). When you want to explore something in between, you have to pause them, remember where you were, you need audio so not development in the middle of the night with your wife sleeping next to you and lots of other downsides.
Also my English pronouncing is far from perfect.
Maybe i will make a video sometime when i really want to show something special, but changes are low.

I'm not a fulltime software developer as i'm also responsible for a part of the network management in the company where i work, but i'll try to do my best to make things as clear as possible for you all.
If someone finds an error in my ways of …
1

Expert Comment

by:krg2
Comment Utility
Excellent work, Japy!

I truly appreciate your tutorial, it is very helpful and provides a good reference
0
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can be easily solved by simply using a graphics creation tool such as Paint, Gimp, or Adobe Photoshop and the Transparency key tool found within the C# program.

To ensure you have the correct amount of space for all form objects needed and even room for adding features down the road, design of your new program becomes the key to a successful build. In keeping with that tradition of design we will need to first layout how we would like our form to look at the end of our project.

For this example we will be creating a mock MP3 Player. I have decided to make the form appear in the shape of a banner with the display information and buttons in the center. Here is how I would like my form to look when it is complete:

 image001.jpg

As you can tell I am not an artist but for the purpose of this article let’s pretend it is the greatest design ever. You can do this step with nothing but a scratch piece of paper and pen just so you have a visual goal to work towards. Next we want to conceptualize a layout on the form to see if it meets your needs.

image002.jpg

Once again, despite the artistry it appears to be in line with my concept.

The next step is where we turn idea into reality. From here going forward…
3
This article introduced a TextBox that supports transparent background.

 TCTextBox demo

Introduction


TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the urge for it. TextBox is among one of them, but unfortunately, once in a while people want it to be transparent (such as this typical question in EE: Transparent TextBox in C#).

If you search on the internet for a solution, you will come across advices like subclassing TextBox and add the support to transparent background color, or, drawing your own background in the OnPaint event. It is rational theoretically but unfeasible practically, as revealed in the following analysis.

(For those who like fast food, you can skip the literature sections and jump to the “Using the Code” section to grab and eat. Actually I also get my hands wet immediately after a short hunting with no luck. After a couple of days working, when I decide to present this home-made component to public, I have to head back to the anatomization part to make the article complete. It costs me much more time than doing the simply coding stuff along.)

The traditional TextBox just refused to be tweaked


To verify the above common suggestions, I build a phantom class TestTextBox derived from TextBox. Again, test cases are flagged in the source code for users who like to practise by themselves.

Set background color as Color.transparent (Test Case 1)
1
LVL 8

Author Comment

by:trestan
Comment Utility
systan, would you mind post the link where you see the same TXTextBox? Did you compare the source code bwtween the two?

It's also normal that not only one person think about the needs and create something similar:)
0
LVL 8

Expert Comment

by:mac-will
Comment Utility
You aren't Disposing your 'SolidBrush' object.

You should wrap the new solidbrush in a using.
0

Summary:

Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to-use code snippet using BinaryFormatter with simple encryption is provided.


Introduction:

I was amazed the first time I read the dotnet documentation about serialization. Prior to the dotnet era, it was a big headache to deal with configuration data. You would have to write large code pieces to stream the data out to a file and then parse the long strings again to find out the proper data to read back. When playing with serialization, I was hoping to create a complete cache of the application and restore it just like nowadays Windows system “Hibernation” feature. Although the reality is always far from the imagination, dotnet serialization is still very useful in caching “part” of an application – the data objects.

Dotnet framework provides two types of serialization: shallow serialization, and deep serialization, represented by
   XmlSerializer in System.Xml.Serialization namespace and
   BinaryFormatter in System.Runtime.Serialization.Formatters.Binary namespace,
respectively. The differences between the two types are obvious: the former is designed to save and load objects in human-readable XML format, and the latter provides compact binary encoding either for…
4
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods.
Demo
Introduction

In one of my applications I needed a control that could be resizable at run time. Just like the canvas in MSPaint, you can resize it inside the host window. After a quick search on the internet I noticed that most solutions treating this simple issue as a beast.  An example of a "complex implementation" is in the EE Solution, here.

Using SendMessage is an intuitive temptation.  We could try the technique I descried in my previous article on how to drag a form -- wehe we simply flood mouse movement to the caption of the host form.  However, the parameters for resizing message scattered to eight directions and you'd have to calculate the delta in each direction to make it work.  That’s why the code tends to become so bulky.


Using PictureBox as decoration

When a control is runtime resizable, you'll certainly want to provide some visual indication to users. You can manually draw an “edge” on the control using graphic functions, and manually change the cursor type when the …
0

Expert Comment

by:Asus314
Comment Utility
can you please share source code of your soft TcPaint ?
Thank you
0

C#

93K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).