C#

94K

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

Following program illustrates the difference between typeof operator and GetType method.  Please see attached compilation error.  Why doesn't it compile?

What are types Type and object in this program?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

// C# program to illustrate the
// difference between typeof
// operator and GetType method

namespace Test_Code
{
    public class CFG
    {
        // Main method
        static public void Main()
        {
            string s = "Geeks";

            // using typeof operator
            Type al = typeof(string);

            // using GetType method
            Type a2 = s.GetType();

            // checking for equality
            // line 27
            Console.WriteLine(a1 == a2);

            // taking a type object
            object obj = "Hello";

            // using typeof operator
            Type b1 = typeof(object);

            // using GetType method
            Type b2 = obj.GetType();

            // checking for equality
            // it will return False as
            // GetType method is used
            // to obtain run-time type
            Console.WriteLine(b1 == b2);
        }
    }
}

Open in new window

error.PNG
0
CompTIA Cloud+
LVL 13
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Hi.
I urgently need help.
How can I shift arrays elements to left ( not using Array.Copy)
Example:
System.Buffer.BlockCopy(pixels1d, Globals.stride, pixels1d, 0, pixels1d.Length - Globals.stride);

Open in new window

here I prepare empty space at the end of pixels1d to write a new values.
Array.Copy and System.Buffer.BlockCopy working fine on PC and laptops but not on tablets.
Just in case you try to convince me how good Array.Copy and System.Buffer.BlockCopy  I tell that they are not fast enough for me using app. on tablet.
0
Hi,
I am working on C#.
I have list and I wanted to get distinct countries.

// Find distinct countries and 
            countries = career.Select(x => x.Country);

Open in new window


Please advise what I am doing wrong?

Below is my code:

 
Feed feed = new Feed();
            List<Career> career = new List<Career>();

            Career careerOne = new Career();
            careerOne.Country = "Australia";
            career.Add(careerOne);

            Career careerTwo = new Career();
            careerTwo.Country = "UK";
            career.Add(careerTwo);

            Career careerThree = new Career();
            careerTwo.Country = "Australia";
            career.Add(careerThree);

            List<Countries> countries = new List<Countries>();

            // Find distinct countries and 
            countries = career.Select(x => x.Country);

Open in new window


public class Feed
    {
        public List<Career> Career { get; set; }
        public List<Countries> countries { get; set; }
    }

Open in new window


public class Career
    {
        public string Country { get; set; }
    }

Open in new window


public class Countries
    {
        public string name;
    }

Open in new window

0
CRM 2013 plugin issue

We are getting a Business Process error when entering information into a specific address field.  The error is below and it indicates a specific plugin.  I am trying to use the plugin profiler to debug the error but I am not getting a log file to download.

The error:

Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: System.Security.SecurityException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #FA546B2ADetail: 
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
  <ErrorCode>-2147220970</ErrorCode>
  <ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />
  <Message>System.Security.SecurityException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #FA546B2A</Message>
  <Timestamp>2019-05-15T16:14:48.6560033Z</Timestamp>
  <InnerFault i:nil="true" />
  <TraceText>

[PluginProfiler.Plugins: PluginProfiler.Plugins.ProfilerPlugin]
[e4515f67-2977-e911-836c-005056aaeab8: CallMuleESB: Update of account (Profiler)]


</TraceText>
</OrganizationServiceFault>

Open in new window

0
Hi,

I have the following code. How can I avoid foreach using linq?

foreach(var number in phoneNumbers)
{
	foreach(var i in number.key)
	{
		if(students[i].phone == null)
		{
			students[i] = new People { phone = number.Value };
		}
		else
		{
			students[i].phone = number.Value;
		}
	}
}

Open in new window


please note
Dictionary<string[], string> phoneNumbers
List<People> students
0
I found some code to sort a 2d array on https://www.codeproject.com/Tips/166236/Sorting-a-Two-Dimensional-Array-in-Csharp
I tried adjusting it to strings which works.  However it treats numbers as strings eg 10 is less than 2.

How can this code be modified to check the type of each column and sort accordingly?
I'd like to be able to sort by multiple criteria for example I may want to sort a list of students by their exam grade (string A-G) and year (7-13).  One sort field is a string.  The other is an integer or could be a date etc.  
The key thing is not to lose the first sort when applying the second sort.  I think this is referred to as a stable sort.
The code calling this routing could specify the data type of the column to be sorted.  This is the sort of signature I have in mind.  The number of columns will vary though.

private void Sort2DArray(int TotalColumns, string FirstColumnToSort, string DataTypeOfFirstColumn,, string SecondColumnToSort, string DataTypeOfSecondColumn,...)
{}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp16
{
    class Program
    {
        static void Main(string[] args)
        {
            string[,] array = new string[3, 3] { { "b", "z", "2" }, { "c", "x", "10" }, { "a", "y", "8" } };

            string[,] sortedByFirstElement = array.OrderBy(x => x[0]);
            string[,] sortedBySecondElement = array.OrderBy(x => x[1]);
         

Open in new window

1
I found this code online to give all permutations of a char array.  Source is https://www.geeksforgeeks.org/c-program-to-print-all-permutations-of-a-given-string-2/
Do you have some code that will do the same with an array of strings eg each element of the string array is a word?
I have added two functions PermuteArray and SwapArray to the code I found online.

class Program
    {
        static void Main(string[] args)
        {
            String str = "ABCD";
            int n = str.Length;
            permute(str, 0, n - 1);
            string[] Arr = new string[] { "The ", "Quick", "Baloo ", "Quotient" };
            int ArrLen = Arr.Length;
            permuteArray(Arr, 0, ArrLen - 1);
        }
        /** 
    * permutation function 
    * @param str string to  
       calculate permutation for 
    * @param l starting index 
    * @param r end index 
    */
        private static void permute(String str,
                                    int l, int r)
        {
            if (l == r)
                Console.WriteLine(str);
            else
            {
                for (int i = l; i <= r; i++)
                {
                    str = swap(str, l, i);
                    permute(str, l + 1, r);
                    str = swap(str, l, i);
                }
            }
        }

                private static void permuteArray(String[] str,
                            int l, int r)
        {

            for (int i = l; i < r; i++)
            {
  

Open in new window

0
Hi Experts,

I am running on dot net 4.6.1

I have the same problem described in the following question

https://stackoverflow.com/questions/21834189/retrieve-display-names-from-validator


Please help ASAP,

Best,
0
Following code sums each row of jagged array.
Is it possible to use nested foreach loop without i and j variables?   Or a better implementation with nested foreach loop?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld2
{
    class Program
    {
        static void Main(string[] args)
        {
            byte i = 0;
            byte j = 0;

            /* array to store sum of each row of two-dimensional jagged array */
            double[] sum = new double[5] { 0, 0, 0, 0, 0 };

            /* Define two-dimensional jagged array */
            double[][] budget;
            budget = new double[5][];

            /* Allocate two-dimensional jagged array */
            budget[0] = new double[2] { 1, 2 };
            budget[1] = new double[3] { 11, 12, 13 };
            budget[2] = new double[1] { 21 };
            budget[3] = new double[4] { 41, 42, 43, 44 };
            budget[4] = new double[2] { 51, 52 };

            /* sum each row */
            foreach (double[] row in budget)
            {
                foreach (double value in budget[i])
                {
                    sum[j] += value;
                }
                i++;
                j++;
            }

            foreach (int result in sum)
            {
                Console.WriteLine(result);
            }

        }
    }
}

Open in new window


output
0
Hi,

I have a question. I have a existing WCF type framework that has like 8 difference .svc's and in each one of those .svc's there are like 40 different web services (methods) that are called.  This is in ASP.NET and C#.

I am going to start implementing REST aspects as well with ASP.NET and C#.

Is it wise to maintain 2 separate frameworks? One for REST methods (could also be 10-20 different methods) and that over existing SOAP svc's? Or do I combine the REST calls/process into the existing WCF?

If the suggestion is 2 separate frameworks... does anybody have an example of how that would be done in REST?

Any information would be greatly appreciated.

Thanks!
0
Become a Microsoft Certified Solutions Expert
LVL 13
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

I have a C# class in Visual Studio 2017 to hold values for columns of a SQL Server 2014 table.  I have a DataSet returned from a stored proc.  Can please you send a code sample that puts the values for each table column from the DataSet into the class that has corresponding names.  If you want the code for the class I can send it.
0
Can someone show me good examples of dependency injection in c#?
0
In this article it says that dependency injection can move errors from compile time to runtime.
https://medium.freecodecamp.org/a-quick-intro-to-dependency-injection-what-it-is-and-when-to-use-it-7578c84fa88f

Under what circumstances can dependency injection cause errors at runtime that would have otherwise been caught at compile time?
How can this risk be reduced?

I'm using Visual Studio 2017 with C#.
0
In the past I have developed applications using C#, ASP.Net Web Forms, Asp.Net MVC 5 , Razor , javascript, css, bootstrap, Entity Framework and SQL Server.
I'm familiar with ASP.NET MVC model.

Now i'm looking at upgrading my skills to ASP.NET Core.

I saw this book.

https://www.amazon.com/Front-end-Development-ASP-NET-Angular-Bootstrap/dp/1119181313/ref=sr_1_4?keywords=asp.net+core+angular&qid=1557595000&s=books&sr=1-4


Which led me to think the following.

If I'm going to create a ASP.NET Core MVC application using Entity Framework with a Sql Server back end....

What is the advantage of bringing in Angular into the mix?

What is the advantage of using Angular + ASP.NetCore MVC + Razor + JavaScript + CSS + Bootstrap + C# + Sql Server?

Rather than just this ASP.NetCore MVC + Razor + JavaScript + CSS + Bootstrap + C# + Sql Server?
0
I have a c# application with a grid defined in a form in the User Interface Layer.

I need to loop through records in the grid in the  Data Access  Layer and save same to the database

The Gridname is dgvDetailsTable  and the .Rows is flagged

See  my Full Script below

public void CreateEducationForm(List<Tuple<string, string, string, string, string>> newTuples)
        {
            using (NpgsqlConnection conn = new NpgsqlConnection(pgrstring))
            {
                using (var command = new NpgsqlCommand("public.speducation_writemasterdetail", conn))
                    //using (var command = new NpgsqlCommand("public.speducation_insert", conn))
                {

                    conn.Open();
                    command.CommandType = CommandType.StoredProcedure;

                    command.Parameters.Add(value: new NpgsqlParameter("staffnox", NpgsqlTypes.NpgsqlDbType.Varchar) { Direction = ParameterDirection.Input, Value = GridVariables.GridColumn01 });
                    command.Parameters.Add(new NpgsqlParameter("companycodex", NpgsqlTypes.NpgsqlDbType.Varchar) { Direction = ParameterDirection.Input, Value = GridVariables.GridColumn07 });
                    command.Parameters.Add(new NpgsqlParameter("empidx", NpgsqlTypes.NpgsqlDbType.Integer) { Direction = ParameterDirection.Input, Value = ((int)GridVariables.GridColumn08) });
                    command.Parameters.Add(new NpgsqlParameter("empeduidx", NpgsqlTypes.NpgsqlDbType.Integer) { 

Open in new window

0
I am trying to write 2 records from a tuple in my c#  application.

The method only writes 1 records and then complains about the parameter being duplicated

See  code below:

public void CreateEducationForm(List<Tuple<string, string, string, string, string>> newTuples)
        {
            //Place  to process tuples into the database
            //  Save Button Click
            using (NpgsqlConnection conn = new NpgsqlConnection(pgrstring))
            {
                // public.speducation_insert
                using (var command = new NpgsqlCommand("public.speducation_writemasterdetail", conn))
                  //using (var command = new NpgsqlCommand("public.speducation_insert", conn))
                {

                    conn.Open();
                    command.CommandType = CommandType.StoredProcedure;

                    command.Parameters.Add(value: new NpgsqlParameter("staffnox", NpgsqlTypes.NpgsqlDbType.Varchar) { Direction = ParameterDirection.Input, Value = GridVariables.GridColumn01 });
                    command.Parameters.Add(new NpgsqlParameter("companycodex", NpgsqlTypes.NpgsqlDbType.Varchar) { Direction = ParameterDirection.Input, Value = GridVariables.GridColumn07 });
                    command.Parameters.Add(new NpgsqlParameter("empidx", NpgsqlTypes.NpgsqlDbType.Integer) { Direction = ParameterDirection.Input, Value = ((int)GridVariables.GridColumn08) });
                    command.Parameters.Add(new NpgsqlParameter("empeduidx", 

Open in new window

0
Hi,

I am a lab instructor at my university doing Data modeling and programming languages classes.

I need a roadmap for my students who want to learn .net programming using c# from zero to hero.

Topics, Curriculum, Frameworks, ....

Please help me and my students!
0
I need to use HTML encode to filter/scrub some data being read by my SqlDataReader object. Trying to prevent an XSS attack. I've never used HTML encode before but I need to apply it to code that looks like the following:

                        oReader = oCmd.ExecuteReader();

                    if (oReader.HasRows == true)
                    {
                        int iLastID = 0;
                        decimal total = 0;

                        while (oReader.Read())
                        {
                            if (iLastID != oReader.GetInt32(oReader.GetOrdinal("checktypeid_fk")))
                            {	                            
                                sTableDetail += "<tr>";
                                sTableDetail += "<TD>" + oReader.GetValue(oReader.GetOrdinal("Description")).ToString() + "</TD>";
                                sTableDetail += "<TD>" + oReader.GetValue(oReader.GetOrdinal("Quantity")).ToString() + "</TD>";
                                sTableDetail += "<TD align=right>$" + oReader.GetValue(oReader.GetOrdinal("Amount")).ToString() + "</TD>";
                                sTableDetail += "<TD align=right>$" + Convert.ToString(Convert.ToDouble(oReader.GetValue(oReader.GetOrdinal("Amount"))) * Convert.ToDouble(oReader.GetValue(oReader.GetOrdinal("Quantity")))) + "</TD></TR>";
                            }
                            else
                            {
                                

Open in new window

0
Hi
I have one more question about app. written on WPF in C#.
I have a problem I don't know how to resolve.
The app. opens from icon on desktop on tablet. It opens by one click (is it any chance to change this?) but sometimes
user try to open it by double click and then opens two instance of my app. It was easy to avoid with VB but I don't know what
I do now. I used this code in App.xaml.cs
 
 private void Application_Startup(object sender, StartupEventArgs e)
        {
            // when application starts, close all windows of previous instance
            for (int i = App.Current.Windows.Count - 1; i >= 0; i--) App.Current.Windows[i].Close();

            // find out previous instance from system process list
            Process current = Process.GetCurrentProcess();
            var running = (from process in Process.GetProcesses()
                           where process.Id != current.Id && process.ProcessName.Equals(current.ProcessName, StringComparison.Ordinal)
                           select process).FirstOrDefault();
            if (running != null) // if found, kill it thoroughly
            {
                if (running.Responding)
                    running.CloseMainWindow();
                else
                    running.Kill();
                running.WaitForExit();
                running.Close();
                Thread.Sleep(1000);
            }

            // handle unhandled exceptions in current domain
            

Open in new window

0
Learn Ruby Fundamentals
LVL 13
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.

hi.
How do I know if the tablet is in Landscape or Portrait mode?
I have an application written in WPF (C#) , the layout looks nice if the tablet is Landscape mode, but for Portrait mode I have to use another layout.
How do I get know app. when layout have to be switched from one to another?
0
I am trying to call a stored procedure in C# that contains both SELECT statements and PRINT statements. I've managed to get the PRINT statements back by way of a SqlInfoMessageEventHandler, but that doesn't help since there are SELECT statements mixed in that contain information pertaining to the PRINT statements.

The other fun part of this is that the SELECT statements all have varying #s and names of columns.

All I really want to do is capture all of that output into a string variable (kinda like executing the stored procedure in SSMS with the query results being output as text.

Changing the Stored Procedure isn't possible.

Is this possible?
0
Hi, I have and application written on WPF (C#) which runs on tablets. In some places user have to input text or value but the application takes the entire screen (Maximised)
Is it any possibility to raise the OnScreenKeyboard from code?
0
I have a c# application with a grid containing 2 records and I want to read the
2 records using  a tuple (see  code below)

public void GetGridData(IEnumerable<Tuple< string, string, string,  string>> tuples)
        {
            var newTuples = new List<Tuple< string, string, string, string>>();

            foreach (var tuple in tuples)
            {

                if (Convert.ToString(dgvDetailsTable.CurrentRow.Cells["dgvtxtschoolname"].Value).Length > 0)
                {
                    (string gc2, string gc3, string gc4, string gc6) = (

                                Convert.ToString(dgvDetailsTable.CurrentRow.Cells["dgvtxtschoolname"].Value),
                                Convert.ToString(dgvDetailsTable.CurrentRow.Cells["dgvstartdate"].Value),
                                Convert.ToString(dgvDetailsTable.CurrentRow.Cells["dgvenddate"].Value),
                                Convert.ToString(dgvDetailsTable.CurrentRow.Cells["dgvcmbdegreecode"].Value)
                             );
               
                    GridVariables.GridColumn02 = gc2;   // School Name
                    GridVariables.GridColumn03 = gc3;   // Start Date
                    GridVariables.GridColumn04 = gc4;   // End date
                    GridVariables.GridColumn06 = gc6;   // Degree Earned
                  
                    newTuples.Add(Tuple.Create(gc2, gc3, gc4, gc6));
                    gc2 = gc3 = gc4 = gc6 = "";
                }
            }
     

Open in new window

0
Hi Experts,

I have this dropdown list. For example it has 4 values , "A, B, C, D"
 @Html.FacetDropDownListWithDefaultFor(m => m.SecretQuestionId, Model.SecretQuestionSelectList, new { @class = "special-dropdown", title = HttpUtility.HtmlDecode(T("Please specify").Text), unselectedvalue = 0 })

Open in new window


I want to pass those 4 to the controller in a hidden field. So I created

@for (int i = 0; i < Model.SecretQuestionSelectList.Count; i++)
{
    @Html.HiddenFor(m => m.SecretQuestionSelectList[i])
}

Open in new window


When I go to the controller, I have 4 items in "SecretQuestionSelectList" but they all are "null".  I want those 4 values "A, B, C, D" to pass to the controller.

Thanks in advance!
0
Hi Experts,

I have a string defined as
public string SecretQuestion{
            get {
                if (SecretQuestionId > 0 && SecretQuestions != null && SecretQuestions.Any()) {
                    return (from s in SecretQuestions where s.SecretQuestionId == SecretQuestionId select s.Value).FirstOrDefault();
                }
                return null;
            }
		}

Open in new window


Right now this string has only get property. How can I add the set property so that I can write value to it.

Thanks in advance!
0

C#

94K

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).