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

I am receiving the following error always when this method is executed through Window Service whether when the same code is executed through Web Portal it is working Fine.

Could not create ssl/tls secure channel. c#


using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;


 void wc1TwoSample2()
        {
            try
            {
                ServicePointManager.ServerCertificateValidationCallback +=
                delegate(Object sender1, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
                {
                    return true;
                };
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.DefaultConnectionLimit = 9999;
                //ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(delegate { return true; });
                string URL = "https:URL";
                string param = "/api/v1/accounts";
                string resp = URL + param;
                var http = 

Open in new window

0
I have working with an Rest api, which returns json data, but not sorted out the way I want. Api is not flexible enough, such that we can pass a sort parameter and it returns the result accordingly.

so, the data in such form

public class records {

....
      public Collection<Item> items ;

.....

}


in my c# code, I do something like this,


var results = CallApi();


var sortedResults = results.OrderBy(x => x.items.price);

return soretedResults.tolist();


I am concerned that this sorting and converting it back to the list , is expensive and as the results
grow larger, this might cause problem.

any thoughts in this?
0
Hi, I'm writing an dll in C#. as long I use functions without argument everything is going fine. Now I have to include function like this
 public void AmChan(int am) to my dll. When I compile code and include dll to the test project this function is invisible; I cannot call it.
But I can see and use functions without argument like this :     public void CleanBuffer(){}
What I'm doing wrong? I use Class Library (.NET Framework).
0
I'm trying to populate a list box and I keep getting the following error.

This is the error!

Here is my code:
     private static void DirectoryCopy(string sDir, string dDir, bool copySubDirs)
        {
            Cursor.Current = Cursors.WaitCursor;

            // Get the subdirectories for the specified directory.
            DirectoryInfo dir = new DirectoryInfo(sDir);

            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException(
                    "Source directory does not exist or could not be found: "
                    + sDir);
            }

            DirectoryInfo[] dirs = dir.GetDirectories();

            // If the destination directory doesn't exist, create it.
            if (!Directory.Exists(dDir))
            {
                Directory.CreateDirectory(dDir);
            }

            // Get the file info for each file in the in the directory
            FileInfo[] files = dir.GetFiles();
            foreach (FileInfo file in files)
            {
                string dst = Path.Combine(dDir, file.Name);
                string src = Path.Combine(sDir, file.Name);

                //Display which file is currently being worked on
                ChangeLabelText(file.Name);

                //use the SafeCopy() function to copy each file until it finishes before copying the next file.
                SafeCopy(src, dst, 10000);

                //add the name of the file that was just copied to the 

Open in new window

1
I am reading an Excel spreadsheet and came across a few dates where the value is "0/0/0000". I want to convert these to "1/1/1901". I have defined defDate as string "1/1"1901"
Every time my code encounters one of these it fails on date = double.Parse(sdate); with a message about invalid format. What must I change to get this to work? In the spreadsheet this column is defined as type date.

                                    if (xlRange.Cells[i, j].Value2.ToString() != "0/0/0000")
                                        sdate = xlRange.Cells[i, j].Value2.ToString();
                                    else
                                        sdate = defDate;

                                    date = double.Parse(sdate);    ---- THIS IS WHAT FAILS -----------

                                    var rdateTime = DateTime.FromOADate(date).ToString("yyyyMMdd");
                                    redistributionLastDate = rdateTime;
0
I have these  4 buttons across on all my c# windows application forms
(Save,Update,Delete and Exit)  see  buttons  below

Display of Buttons on ALL forms in my c
On 1 on the forms  I have done the following which works as desired.

1. on form_load  I  call a library  that accesses  the database to determine whether a button should be visible or not
see the form_load  call to the library below:

1. In my Form-Load Event

 FormPermissionsProcessor processor = new FormPermissionsProcessor();
 var result = processor.GetFormExecStatus();
 SetButtons();


2. In my Library the status each button is determined after reading this from a database

  public class FormPermissionsProcessor
    {
       
       
        public Tuple<string, string, string,string> GetFormExecStatus()
        {
            PermissionsModel model = new PermissionsModel();

            GlobalConfig.Connection.GetFormPermissions();       // This line goes into the database to fetch the variables below
            string libregstatus = LoginDetails.staticformexecute;
            string libreglevel =  LoginDetails.staticaddbutton;
            string liblicensetype = LoginDetails.staticupdatebutton;
            string libdel = LoginDetails.staticdeletebutton;

            return new Tuple<string, string, string,string>(libregstatus, libreglevel, liblicensetype,libdel);
        }
       
    }

Open in new window


3. Method in my form that processes the returned values

 private void SetButtons()
        {
            saveButton.Visible = false;
            updateButton.Visible = false;
            deleteButton.Visible = false;
            if (LoginDetails.staticaddbutton == "Y")
            {
                saveButton.Visible = true;
            }
            if (LoginDetails.staticupdatebutton == "Y")
            {
                updateButton.Visible = true;
            }
            if (LoginDetails.staticdeletebutton == "Y")
            {
                deleteButton.Visible = true;
            }
        }

Open in new window


Currently  this process works for 1 form but i don't want to be repeating
the method in 3 above on  every form

How can I achieve this particularly since the 4 buttons (Save,Update,Delete and Exit) are local to each form

Thanks

Olukay
0
Hi,
how to deactivate session using C#. I don't want any web.configuration settings . I like to deactivate the session from C# code.

var sessionID = HttpContext.Current.Session.SessionID;
if (HttpContext.Current.Session["UserID"] == null) // for example....
              {
                  <<<NEED TO DEACTIVATE SESSION HERE>>>
              }

i tried Session.Abandon(), it is not working.

Kind regards,
Pooja
0
I have the  c#  method stated below:

var reader = command.ExecuteReader();
                    if (reader.Read())
                    {
                        if ((string)reader?["formexecutex"] != null)
                        {
                            LoginDetails.staticformexecute = (string)reader["formexecutex"];
                            LoginDetails.staticaddbutton = (string)reader["addbuttonx"];
                            LoginDetails.staticupdatebutton = (string)reader["updatebuttonx"];
                            LoginDetails.staticdeletebutton = (string)reader["deletebuttonx"];

                            results.Add(model);
                        }
                        else
                        {
                            StandardMessages.FormPermission();
                        }
                    }

Open in new window


During Execution  variable formexecutex can be   "Y" ,  "N"  OR may not even exist  ie is DBNull

How do handle the  DBNull  case to use the else  clause of the If Statement

See  the error i got while trying

Hod do I Handle a DBnull  Error
Thanks

Olukay
0
Hi,

I am working on .net using c#

I am posting data in method PostAsJsonAsync using package System.Net.Http.

Please advise me with my findings.

I am getting  response as

ReasonPhrase = "Unauthorized" string
StatusCode = "BadRequest" System.Net.HttpStatusCode

Not sure but looks to me that url(https://edg-dev-sit.dfdegg.net/loyalty/identity/v2/ssotoken) where I am submitting the data is not allowing data to be submitted from myside.

or Allow origin is not done.

I am not sure. Please help me with my finding.

My code is
HttpResponseMessage response = mHttpClient.PostAsJsonAsync<T>(uri.ToString(), data).Result;

where 
uri.ToString() is https://edg-dev-sit.dfdegg.net/loyalty/identity/v2/ssotoken

and data is { grantType = "authorization_code", authorizationCode = "umKTS4bKXOedNSjuv2rq" }

Open in new window



mHttpClient is as follows:

System.Net.Http
private HttpClient mHttpClient = null;

mHttpClient = new HttpClient(httpClientHandler)
            {
                Timeout = timeout,
                DefaultRequestHeaders =
                {
                    AcceptEncoding =
                    {
                        StringWithQualityHeaderValue.Parse("gzip"),
                        StringWithQualityHeaderValue.Parse("deflate")
                    },
                    CacheControl = new CacheControlHeaderValue() { NoCache = true }
                }
            };

Open in new window


My response (HttpResponseMessage response) is as follows.
See screenshot attached.


Open in new window

0
I have the following method (below)  in my c# application

 
  public List<PermissionsModel> GetFormPermissions()
        {
            //List<Models.GeneralSetup.PermissionsModel> results = new List<Models.GeneralSetup.PermissionsModel>();
            List<PermissionsModel> results = new List<PermissionsModel>();
            using (var conn = new NpgsqlConnection(pgrstring))
            {
                using (var command = new NpgsqlCommand("public.sppermissions_getforrole", conn))
                {
              
                    conn.Open();
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.Add(new NpgsqlParameter("companycodex", NpgsqlTypes.NpgsqlDbType.Varchar) { Direction = ParameterDirection.Input, Value = LoginDetails.staticcompany });
                    command.Parameters.Add(new NpgsqlParameter("formnamex", NpgsqlTypes.NpgsqlDbType.Varchar) { Direction = ParameterDirection.Input, Value = LoginDetails.staticformname });
                    command.Parameters.Add(new NpgsqlParameter("rolex", NpgsqlTypes.NpgsqlDbType.Varchar) { Direction = ParameterDirection.Input, Value = LoginDetails.staticrole });
                    command.Parameters.Add(new NpgsqlParameter("formexecutex", NpgsqlTypes.NpgsqlDbType.Varchar) { Direction = ParameterDirection.Output });
                    command.Parameters.Add(new NpgsqlParameter("addbuttonx", NpgsqlTypes.NpgsqlDbType.Varchar) { Direction = 

Open in new window

0
Hi
I'm using MS Visual Studio 2019!

working through 20483-Programming-in-C-Sharp training course I'm at Module 7: Accessing a Database
and looking at the demo from here

@step 9 "Add New Item – FourthCoffee.Employees dialog box click ADO.NET Entity Data Model, "  I don't see this  searching "ADO" or "Entity" finds ZERO

I thought I might need a Nuget package   so Search for ADO and installed EntityFramework 6.2.0  resulting in Errors

Severity      Code      Description      Project      File      Line      Suppression State
Message      IDE0060      Remove unused parameter 'args'      FourthCoffee.Employees      E:\VB\20483-Programming-in-C-Sharp-master\Allfiles\Mod07\Democode\Demo1\Starter\FourthCoffee.Employees\FourthCoffee.Employees\Program.cs      7      Active
AND

Severity      Code      Description      Project      File      Line      Suppression State
Warning      NU1701      Package 'EntityFramework 6.2.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETCoreApp,Version=v2.1'. This package may not be fully compatible with your project.      FourthCoffee.Employees      E:\VB\20483-Programming-in-C-Sharp-master\Allfiles\Mod07\Democode\Demo1\Starter\FourthCoffee.Employees\FourthCoffee.Employees\FourthCoffee.Employees.csproj      1      

Any suggestion where to find ADO.NET Entity Data Model as I can't proceed to the course exercise as this is doing similar

BTW: If you attempt this @  1 copy the FourthCoffee.sql file to "C:\Users\User.Name" before running SetupFourthCoffeeDB.cmd.
0
We have an issue when loading a website on our IIS server. Is anyone able to advise where we start in resolving this?

For reference, we have removed the server from the domain and re-joined it in the hopes this would help, but it hasn't made any difference.

IIS Server connects to a separate SQL server for its database.

error
We are also seeing an ASP.NET issue in the event log:

Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 7/18/2019 1:54:10 PM
Event time (UTC): 7/18/2019 12:54:10 PM
Event ID: 9eec4075582648cbae1807c776b5b714
Event sequence: 8
Event occurrence: 7
Event detail code: 0
 
Application information:
    Application domain: /LM/W3SVC/1/ROOT/WebaBILLityPro-1-132079278328427605
    Trust level: Full
    Application Virtual Path: /WebaBILLityPro
    Application Path: C:\inetpub\wwwroot\WebaBILLityPro\
    Machine name: WEB-ABILITY
 
Process information:
    Process ID: 3068
    Process name: w3wp.exe
    Account name: IIS APPPOOL\.NET v4.5
 
Exception information:
    Exception type: Win32Exception
    Exception message: No authority could be contacted for authentication

 
 
Request information:
    Request URL: https://billing.intechtelecom.co.uk:443/WebaBILLityPro/Login.aspx?z=fafe553b-315e-4920-aecf-d35b4c72c6cb&z=fafe553b-315e-4920-aecf-d35b4c72c6cb 
    Request path: /WebaBILLityPro/Login.aspx
    User host address: 51.52.75.191
    User:  
    …
0
I have a c# windows form application that is not logging correctly. When I create a situation for the exception to happen, I have a MessageBox.show that is readable:

MessageBox with Exception task
But when I write this to a log I get this text:

S191Ae24.IO.4ileNoA4oun18ExcepAion: Coul18 noA 4in18 4ile C:UsersSteveWDesktopsDirduhDefault.ivb.
4ile na24e: C:UsersSteveWDesktopsDirduhDefault.ivb
   aA S191Ae24.IO.__Error.WinIOError(InA32 errorCo18e, SArinA.D. 24a19be4ullPaA6)
   aA S191Ae24.IO.4ile.SeAAAMribuAe1(SArinA.D. paA6, 4ileAAMribuAe1 4ileAAMribuAe1)
   aA De4aulA_ivb_Up18aAerII.4r247ain.ReplaceExi1AinA.D.De4aulA() in C:U1er1SAeveWDocu24enA1GiAlab_ProjecA1De4aulA_ivb_Up18aAerIIDe4aulA_ivb_Up18aAerIIFr247ain.c1:line 124

Here is the code I'm using:

for the log:
using System.IO;

namespace Default_ivb_UpdaterII
{
    public class LogIt
    {
        readonly GloFun GF = new GloFun();

        public void Message(string message, string fName)
        {
            GF.sDir = Properties.dir.Default.sDir;
            GF.lDir = Path.Combine(GF.sDir, "logs");
            if (!Directory.Exists(GF.lDir))
            {
                Directory.CreateDirectory(GF.lDir);
            }
            string lDir = GF.lDir;
            string lFile = System.IO.Path.Combine(lDir, fName);
            if (!File.Exists(lFile))
            {
                System.IO.File.Create(lFile).Dispose();
                System.IO.File.SetAttributes(lFile, 

Open in new window

0
Hi,

C# Winforms app querying Sharepoint Online using the CSOM Sharepoint Client Classes.

All good so far but I need to get the permissions for the current user so I can check if they have access to the website and/or subsite. I'm connecting to my 'ClientContext' correctly and am using an AD Service Account which has permission to access all sites.

I've found several examples on the web that all give this example of how to retrieve the permissions for the current user:

User user = cxt.Site.RootWeb.EnsureUser(UserPrincipal.Current.EmailAddress);
cxt.Load(user);
cxt.ExecuteQuery();

 // Get all permissions for this user             
var permissions = cxt.Site.RootWeb.GetUserEffectivePermissions(user.LoginName);
 cxt.ExecuteQuery();

Open in new window


The line in bold fails with an 'unauthorized access exception'. The current user in this scenario is myself and I have permissions to open and view all sites except 1 test site.

My Context 'cxt' is running under the service account.

So, in effect I understand this as: run the context as the service account and then load a user and check their permissions, but it doesn't work.

Is it possible what I'm trying to do or is there another way? I've seen mentioned that you have to build a Web API to perform the user permission check because it's allowed to run with 'elevated permissions'.

Hope someone can help?

Thanks,

Mike.
0
I'm currently running a Windows 10, version 1903. My IDE is MSVS 2019 Community. I'm creating a Windows Form application using the c# language. I have been trying to use the default windows file copy progress dialog in my windows application. But have had some issues. The files copy as they should but the dialog just doesn't show up reliably. Sometimes it does, sometimes it doesn't. The work flow is as follows:

  • Copy the existing "Default.ivb" file in the destination directory to the archive directory as "replaced_on_2019-07-12_152643_Default" so we don't ever lose that file.
  • The file in the destination directory is then deleted.
  • Then copy the updated "Default.ivb" file from the network share to the destination directory.

I use two different subroutines to complete these tasks, these include:
private void DestToArchive()
        {
            try
            {
                logIt.Message("---STARTED UPDATE---" + " | " + DateTime.Now.ToString("yyyy-MM-dd_HH:mm:ss tt" + Environment.NewLine), "log.txt");

                File.SetAttributes(GF.dPath, FileAttributes.Normal);
                Microsoft.VisualBasic.FileIO.FileSystem.CopyFile(GF.dPath, GF.rPath, UIOption.AllDialogs, UICancelOption.DoNothing);
                Application.DoEvents(); //I tried running with and without the do events and it made no difference on either file transfer.

                Thread.Sleep(1000);

                

Open in new window

0
How do I implement the CanViewAll method to check whether it’s possible to view all moves or if there is an overlap between the start and finish times?  This is from a test which I've already completed.  I had to skip this question.

using System;
using System.Collections.Generic;
public class Movie
{
    public DateTime Start { get; private set; }
    public DateTime End { get; private set; }

    public Movie(DateTime start, DateTime end)
    {
        this.Start = start;
        this.End = end;
    }
}

public static class MovieNight
{
    public static bool CanViewAll(IEnumerable<Movie> movies)
    {
        
        foreach (Movie  m in movies)
        {

        }
    }

    public static void Main(string[] args)
    {
        var format = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat;

        Movie[] movies = new Movie[]
        {
            new Movie(DateTime.Parse("1/1/2015 20:00", format), DateTime.Parse("1/1/2015 21:30", format)),
            new Movie(DateTime.Parse("1/1/2015 23:10", format), DateTime.Parse("1/1/2015 23:30", format)),
            new Movie(DateTime.Parse("1/1/2015 21:30", format), DateTime.Parse("1/1/2015 23:00", format))
        };

        Console.WriteLine(MovieNight.CanViewAll(movies));
    }
}

Open in new window

0
ASP.net Web Work In Visual Studio How To Create an Efficient and FAST Setup To Develop...

Open to Any and All Tips that will help me develop DotNet websites faster and easier in Visual Studio...

So FAR... I do the following to be fast/efficient using VStudio .net coding  (not saying this is best or right way --  just providing a starting point)

I have THREE monitors...

Left Monitor has my CSS page and a minimized SQL Server Studio Management Software With my databases and tables to create update etc.

Middle Monitor has Visual Studio 2015 with HTML & ASP.net objects & Code Behind Page + HTML objects and Bookmark folder on my browser with links to
              StackOverflow, Microsoft Docs, and a lot of other DotNet resources... etc.

Right Monitor has Webpage(s) i am working on to see updates made in CSS or Code or HTML or where ever... and interactive web page cheat sheets minimized.

I have a notebook with Cheat Sheet for HTML and CSS printed out from helpful websites... mostly memorized but at my hand if needed

I have chrome developer tools ready to use to help see my or others CSS / HTM code development and to debug... Looking into to Firebug for JS debugging...

I use the Visual Studio block commenter buttons - for comment out comment in actions - to speed up  large comment in or out efforts

I use the Find button inside Visual Studio to see if CSS styles are being used or not in my HTML by searching ALL open …
0
Hello all!  Am having an issue with a web service that I'm trying to debug but it will not "play" within Visual Studio and I can not connect to it on the server with WCF Test client or a test application though adding the service to the test application does work and only breaks when building the application.  The weird thing is that it is currently working in production.  The errors I am getting are a variation of the same...

c:\Users\main\AppData\Local\Temp\Test Client Projects\16.0\908eb97f-72d0-4b17-882a-baac49b3143c\Client.cs(23168,26) : error CS0534: 'System.Data.EntityClient.EntityConnection' does not implement inherited abstract member 'System.Data.Common.DbConnection.ConnectionString.get'
c:\Users\main\AppData\Local\Temp\Test Client Projects\16.0\908eb97f-72d0-4b17-882a-baac49b3143c\Client.cs(23168,26) : error CS0534: 'System.Data.EntityClient.EntityConnection' does not implement inherited abstract member 'System.Data.Common.DbConnection.ConnectionString.set'
c:\Users\main\AppData\Local\Temp\Test Client Projects\16.0\908eb97f-72d0-4b17-882a-baac49b3143c\Client.cs(23168,26) : error CS0534: 'System.Data.EntityClient.EntityConnection' does not implement inherited abstract member 'System.Data.Common.DbConnection.Database.get'
c:\Users\main\AppData\Local\Temp\Test Client Projects\16.0\908eb97f-72d0-4b17-882a-baac49b3143c\Client.cs(23168,26) : error CS0534: 'System.Data.EntityClient.EntityConnection' does not implement inherited abstract member 

Open in new window

0
What is the future of VB.NET with .CORE?

Is .CORE only supporting C#?

Is VB.NET becoming obsolete?

Is .CORE replacing webforms?

What is the future of vb.net and webforms?

thanks!
0
In my c# application i have a method  as  below;

 
private void GetLicenseStatus()
        {
            string libregstatus = txtRegStatus.Text;
            string libreglevel = txtRegisteredLevel.Text;
            string liblicensetype = txtLicenseType.Text;
        }

Open in new window


When i called the method   with  GetLicenseStatus();  I got the required results in the 3 string variables.

Now I want to comment out the method and put in a class  library  so that the 3 string variable values will be
available to other parts of my application.  Below see  the class library definition.

2. Movement of Method to Class Library

namespace DRYDemoLibrary
{
   public  class RevisedActiveLockProcessor
   {
        public string GetLicenseStatus(regstat,reglev,reglicense)
        {
            string libregstatus = txtRegStatus;
            string libreglevel = txtRegisteredLevel;
            string liblicensetype = txtLicenseType;
        }
    }
}

Open in new window


Below  is the error screen i got when trying to get the method into a library

Error Screen moving a method to a Library


What  am i doing wrong and how do i move  this local method into  a class library
with the appropriate call statement from other parts of my application

Thanks

Olukay
0
<button class="btn btn-xs" ng-click="dateRangeSelectionBox.submit()" ng-disabled="!showText">Submit</button>

The button works correctly on click. How to make it work the same on hitting ENTER?

Thanks.
0
I have a c#  application and need to return 2 items from a class  library

when i had 1 item i was able to return it but some how i am having error returning 2 items

The 2  items i want returned are   RegisteredStatus  and RegisteredLevel

Both variables  were defined as  strings  ie

string RegisteredStatus = "";
string RegisteredLevel ="";

After  some processing  in the script ,  I have values in both variables which i want returned.

1. Part of my code in the Library

  MyActiveLock.KeyStoreType = ActiveLock3_6NET.IActiveLock.LicStoreType.alsFile;


            MyActiveLock.Acquire(ref strMsg, ref strRemainingTrialDays, ref strRemainingTrialRuns, ref strTrialLength,
                   ref strUsedDays, ref strExpirationDate, ref strRegisteredUser, ref strRegisteredLevel, ref strLicenseClass,
                   ref strMaxCount, ref strLicenseFileType, ref strLicenseType, ref strUsedLockType);

            if (strMsg != null && strMsg.Length > 0) //There's a trial
            {
                RegisteredStatus = "Trial Mode";
                RegisteredLevel = strRegisteredLevel;
            }
            else
            {

                //cmdKillTrial.Visible = false;
                //cmdResetTrial.Visible = false;
                RegisteredStatus = "Registered";
                RegisteredLevel = strRegisteredLevel;        
            }
            return (RegisteredStatus, RegisteredLevel);

Open in new window


Return RegisteredStatus   worked  fine,  while Return (RegisteredStatus, RegisteredLevel) gave a syntax error

I  introduced  the Tuple below into library hoping it would help me return the 2 values

But i think i might not be calling/using the tuple properly  (see Below the tuple in the library)

2. A Tuple also defined in the Library

 
public static Tuple<string, string> Location(string RegisteredStatus, string RegisteredLevel)
        {
            return new Tuple<string, string>(RegisteredStatus, RegisteredLevel);
        }

Open in new window



3. Eventually in my application i need to get the 2 returned variables in to

some text field on the screen .

For the 1 variable   which worked  my script was

 ActiveLockProcessor processor = new ActiveLockProcessor();
 txtRegStatus.Text = processor.GenerateActiveLockStatus();

What would be the correct syntax now for getting the 2 variables to my Text fields on screen

Please NOTE that i do not have to use Tuples if there is a simpler and more straight way to achieve this.

Thanks

Olukay
0
I am reading an Excel spreadsheet and all was fine until I came to a date field. There are what appear to be several dates fields but they are actually defined as General.  This one column is actually defined as date.

                                    createdDate = xlRange.Cells[i, j].Value2.ToString();
                                    MessageBox.Show("The item created date is : " + createdDate.ToString());

When I run the code and it hits this what I get for value of createdDate is 42795 instead of 03/01/2019, which is the value in the spreadsheet. How do I handle this conversion so I will see 03/01/2019? I have tried putting format strings inside ToString() but all I get is the text for the format string.
0
Why is the grandfather method called when it's virtual and the child method is override?
I've looked on https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/knowing-when-to-use-override-and-new-keywords
It tells me what happens, but I'm struggling to understand the rationale of why Microsoft made it work in this way.

 public class GrandFatherClass
    {
        public virtual void Method1()
        {
            Console.WriteLine("GrandFatherClass.Method1");
        }
        public virtual void Method2()
        {
            Console.WriteLine("GrandFatherClass.Method2");
        }
    }

    public class FatherClass : GrandFatherClass
    {
        public override void Method1()
        {
            Console.WriteLine("FatherClass.Method1");
        }
        public virtual void Method2()
        {
            Console.WriteLine("FatherClass.Method2");
        }
    }
    public class ChildClass : FatherClass
    {
        public override void Method1()
        {
            Console.WriteLine("ChildClass.Method1");
        }
        public override void Method2()
        {
            Console.WriteLine("ChildClass.Method2");
        }
    }
    public class Program
    {
        public static void Main(string[] args)
        {

            Console.WriteLine("BaseClass test = new DerivedClass()");
            GrandFatherClass test = new FatherClass();
            test.Method1();
            test.Method2();
            

Open in new window

0
Can anyone tell me how to compare 2 data tables and update the field if they are not match.

Example.
Table 1
Loan#       TaxReturn  BankStatement
123456     Y                  null
234567     N                 N

Table 2
Loan#       TaxReturn  BankStatement
123456     Y                  Y
234567     Y                  Y

if the Table1.TaxReturn not equal Table2.TaxReturn then use the Table2 value to update the Table1.
if the Table1.BankStatement not equal Table2.BankStatement then use the Table2 value to update the Table1.

it is ok to use Linq if the speed is faster.

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