We help IT Professionals succeed at work.

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

I have placed a datagridview called  dgvTransferPOs onto a Winform using C#. What is being displayed is a list of purchase order numbers resulting from a SQL query. One of the columns in the query is called IsClosed. What I need is to change the color of the row to red if IsClosed = 1 otherwise use the default color if IsClosed =0. The dgv displays 10 records at a time. So if there are 20 records and the user scrolls down, the color needs to move as the slider is moved.
0
Hi

I have some methods that I want to restrict the parameters to allow only Control and Form objects.

I know I can use restrictions, but only one class, and multiple interfaces.

public static void SetWidth<T>(T thisObj, int width) where T: Control
         {
            thisObj.Width=width;
         }

Open in new window


How can I extend the where T: to include Form also ?
0
I am diving into MVC and hit a snag.

In my home controller I am populating a ViewBag. Then I am trying to put that into a drop down list

Home controller:

 
string _connectionString = WebConfigurationManager.ConnectionStrings["xxxxxxx"].ToString();

            using (SqlConnection con = new SqlConnection(_connectionString))
            {
                //
                // Open the SqlConnection.
                //
                con.Open();
                //
                // The following code uses an SqlCommand based on the SqlConnection.
                //

            
                SqlDataAdapter _da = new SqlDataAdapter("Select Name from AspNetRoles", con);
                DataTable _dt = new DataTable();


                _da.Fill(_dt);
                
                ViewBag.RoleList = new SelectList(_dt.AsEnumerable());

                
                con.Close();
                
            }

Open in new window


Index.html :
 
@Html.DropDownList("Name", (IEnumerable<SelectListItem>)ViewBag.RoleList, "Select an application", "Name")

Open in new window



My dropdown populates the correct number of rows, however the proper text does not come up=> system.data.datarow is there 6 times

I am sure I am not converting something....can you help me with this easy newbie question?
0
I have this Grid in my c# application

The Display Value in column 1  has an ID and Description  ( see  screen below)

Selected Record From Combo Box withing Grid

When i change values in column1 I want the description written into column2

I am trying to use LINQ  and a LAMDA Expression  . My script is as shown below

[private void dgvDetailsTable_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {

                switch (this.dgvDetailsTable.Columns[e.ColumnIndex].Name)
                {
                    case "dgvcmbarsaleditemid":
                        var result = ((List<InventoryItemModel>)dgvcmbarsaleditemid.DataSource).Find(x => x.INVITEMId.Equals(dgvcmbarsaleditemid.Selected));
                        this.dgvDetailsTable.CurrentRow.Cells[2].Value = result.INVITEMDescription;
                       

                        break;


                }
            }
        }[/code]

My database  field name is INVITEMId   and my   DataGrid  column 1 name is   dgvcmbarsaleditemid.


In the debugger  I can see that the 1188 records  were selected  and in the debugger i can see the loop search going on

See  Debugger  Screen below

Debugger Screen showing that I have ALL the 1188 records in my List

At the end of the looping it can not find the selected record and put it in the result variable even though the selected record
is on screen and coming from the database.  See  Error screen below

Error Screen with result  variable having null
0
using C# remove the root node in an xml
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://www.w3.org/2001/XMLSchema-instance"><Member xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <LastName>Bond</LastName>
  <FirstName>James</FirstName>
  <AltKey>000011101</AltKey>
  <HCFANbr>000011101</HCFANbr>
  <ContractNbr>000011101</ContractNbr>
  <YmdBirth>2001-06-14T00:00:00</YmdBirth>
</Member></string>      

I want to remove
<string xmlns="http://www.w3.org/2001/XMLSchema-instance">
and
</string>      
so it will look like this:

<?xml version="1.0" encoding="utf-8"?>
<Member xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <LastName>Bond</LastName>
  <FirstName>James</FirstName>
  <AltKey>000011101</AltKey>
  <HCFANbr>000011101</HCFANbr>
  <ContractNbr>000011101</ContractNbr>
  <YmdBirth>2001-06-14T00:00:00</YmdBirth>
</Member>
0
I am creating an application using C# and WPF.  I am using the WebBrowswer control, but it seems to be running an older version of IE.  Is it possible to change it to use a newer version of IE or Edge?  It is also my understanding that the WebBrowser Control in WPF is different from the version in a traditional Windows.Forms application.  Any assistance would be greatly appreciated.  Thanks!
0
Hi,

I am working on C#, ASP.net application.


I am getting IQueryable<byte[]> from the query.
I need byte[] bytes to pass into the method Read to get the real document.

Please advise the solution


IQueryable<byte[]> AWBFile = from x in repository.Select() where x.OrderCode == ordercode && x.TrackingNumber == trackingNumber select x.AWBimagefile;

byte[] bytes = AWBFile //  Get bytes[] from here
docFromUrl.Read(bytes);

Open in new window


Thanks
0
Could someone please tell me how I can resolve this error? This error that I've been receiving from my Production environment does not tell me exactly where or what page in my ASP.NET web app causes the error:

Invalid URI: The hostname could not be parsed.

at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Web.Util.UriUtil.BuildUriImpl(String scheme, String serverName, String port, String path, String queryString, Boolean useLegacyRequestUrlGeneration)
at System.Web.HttpRequest.BuildUrl(Func`1 pathAccessor)
at System.Web.HttpRequest.get_Url()
at System.Web.Http.WebHost.HttpControllerHandler.ConvertRequest(HttpContextBase httpContextBase, IHostBufferPolicySelector policySelector)
at System.Web.Http.WebHost.Routing.HttpContextBaseExtensions.GetOrCreateHttpRequestMessage(HttpContextBase context)
at System.Web.Http.WebHost.Routing.HttpRouteExceptionHandler.d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.TaskAsyncHelper.EndTask(IAsyncResult ar)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Open in new window


Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36


Many thanks in advance.
0
In my c# application I am trying to get values from a combox withing a grid
to populate other text fields in the same Grid

My Source Table is an Inventory table as shown below

Inventory Table Showing some property names and the Data

and I have populated a  combo box withing the grid with the code below

dgvcmbarsaleditemid.DataSource = null;
  dgvcmbarsaleditemid.DataSource = GlobalConfig.Connection.GetInventoryItems_All();
  dgvcmbarsaleditemid.DisplayMember = "FullCodeName";
  dgvcmbarsaleditemid.ValueMember = "INVITEMId";

I only have 2 fields in the combo  ( ie public string FullCodeName => $"{INVITEMId}  {INVITEMDescription }   ";  )

The Grid I am trying to populate is shown below with the first column showing data in the combo

DataGrid to be populated BUT with the Combo in Column 1 already loaded
I tried to Cast data from the Combo box so that i can now have access  to all the other properties  in inventory table with the script below

[private void dgvDetailsTable_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {

                switch (this.dgvDetailsTable.Columns[e.ColumnIndex].Name)
                {
                    case "dgvcmbarsaleditemid":
                        var selectedComboRecord = (InventoryItemModel)dgvcmbarsaleditemid.DataSource;
                        this.dgvDetailsTable.CurrentRow.Cells[2].Value = selectedComboRecord.INVITEMDescription;

                        break;


                }
            }
        …
0
Hi

I want to change source code using Roslyn.

I'm using this code now for testing, and will overwrite every property. But dont worry about that:

public override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax node)
         {
            // remake property with the values from incoming node
            var changedProp =
                 SyntaxFactory.PropertyDeclaration(
                    node.Type,
                    node.Identifier.ValueText + " "
                 )
                 .AddAccessorListAccessors(
                  SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
                  SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
                  );

            foreach (var modifier in node.Modifiers)
            {
               changedProp = changedProp.AddModifiers(modifier);
            }

            return changedProp;
         }

Open in new window


What I want to do is change code like this:

      internal string Heading
      {
         get
         {
            string HeadingRet = myActivity.Heading;
            return HeadingRet;
         }

         set
         {
            myActivity.Heading = value.substring(0,20);
         }
      }

Open in new window


to

      internal string Heading { get => myActivity.Heading; set => myActivity.Heading = value.substring(0,20); }

Open in new window


My code will just change to:

internal string Heading {get; set;}

Open in new window


What I dont understand is how to make: get => variable; set => variable = value; with Roslyn.

BTW: I will not do this at runtime, but change the source code files for improved code. I'm not looking for personal views on this kind of coding, unless it's fundamentally wrong. And not looking for utilities since they are not flexible enough to do exactly what I want. I want to code the transformation.
0
See attached image for general idea about the structure...

I have a c# website built on IIS on SERVER01, and the website webform has the function as attached in image 1

public static string[,] ServiceInstalledList(string machineName)
        { 
            // get list of Windows services
            ServiceController[] services = ServiceController.GetServices(machineName);
            string[,] serviceList = new string[services.Length, 5]; 
            int i=0;
            // try to find service name
            foreach (ServiceController service in services)
            {
                serviceList[i, 0] = service.ServiceName;
                serviceList[i, 1] = service.Status.ToString();
                serviceList[i, 2] = service.DisplayName.ToString();
                serviceList[i, 3] = service.MachineName.ToString();
                serviceList[i, 4] = service.StartType.ToString();
                i = i + 1;
                // if (service.ServiceName == serviceName)
                //    return true; 
            } 
            return serviceList;
        }

Open in new window



It is working as expected when the "machineName" is local "SERVER01", it shows the list services on the server.

But when I change the machineName to a remote server (server host name or server IP address) in the same network (10.0.0.0/24),  I got the error attached in the send image.

The error shows the website can reach to the server and can see it, but it does not have the access only. It is something related to security, passwords ...etc.



[Win32Exception (0x80004005): Access is denied]

[InvalidOperationException: Cannot open Service Control Manager on computer 'SERVER02'. This operation might require other privileges.]
   System.ServiceProcess.ServiceController.GetDataBaseHandleWithAccess(String machineName, Int32 serviceControlManaqerAccess) +51781
   System.ServiceProcess.ServiceController.GetServicesOfType(String machineName, Int32 serviceType) +183

Open in new window

123.PNG
122.PNG
124.PNG
0
The owner of the company has been working on upgrading the Windows Forms application for the past 5 years. He wrote the first one in 2002 with Web Services and he decided he wants a new version using new look-and-feel with WCF and not Web Services.

He's  given me the code to continue with this insanity :)

Code compiles, runs, I can log in but then code doesn't connect to WCF. I put debug steps in WCF and it doesn't even stop in the code.

I'll go step by step

1. This is how the project is set up :

ee1.png
2. I run the code, log in, try some functionality and I get this error:

ee2.png
3.  Looked at IIS Express and I see these running
ee3.png
4. I don't see http://localhost:63680/SBTechTeamMembersService.svc in the list

5. I tried http://localhost:53457/ (this is in the list in step #3) in the browser and I see a list of code
    I tried  http://localhost:63680/ and I get page cannot be displayed.


So, the WCF is not running? If so, how can I start it? why the other WCFs are in the list and this one isn't?
0
I have a set of files that I am working with.  Some of the files have extensions (jpg, gif, png, etc.) and some do not.  Is it possible to determine the file extensions for the files that don’t have them?
0
Dear Experts
Based on the business processes we have identified solution development to be done in .NET Core framework with  Visual Studio using C# and MSSQL we have decided power BI for reporting and analytics( on-premise power BI report server) but customer have asked if possible to consider PostgreSQL, please help to understand on following
1.Application developing using .NET Core framework with Visual Studio using C# instead of MSSQL for database going for PostgreSQL will there be any complications, limitations and some thing that we have to comprise.
2.If we chose PostgreSQL as database server and front end application .NET Core framework with Visual Studio using C# and develop application but using power BI for reporting and analytics is there going to be any challenges, does power BI has connector to interface with PostgreSQL please let us know ,
Please help on above 1 and 2
0
I am getting an error when trying to run my solution. It will build successfully.  The error occurs when trying to access the Web Applications.  I have added myself to Farm Admin, Local Admin, WSS_ADMIN_WPG. When I run the solution, I can access the Central Administration root URL, but when it tries to traverse to lower sites in CA, I get the same error.  All the other Web applications are denied at the top level.

I can run a PowerShell script on the same server and get the response with ALL Web Applications URL's with no errors.

Error:
Activated Event Time Duration Thread
Exception: Exception thrown: 'System.UnauthorizedAccessException' in Microsoft.SharePoint.dll ("Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"). Exception thrown: 'System.UnauthorizedAccessException' in Microsoft.SharePoint.dll ("Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))") 4.73s [13952] <No Name>
0
Hi,

I am trying to get the length from a field in SQL

if (reader["CCR"].ToString().Length == 0)
 A
else
B

Is this syntax correct? I know the length count is 5 but it keeps showing me A.  thanks
0
Can we create a extension method ToVauleOrDefault on the DataReader, so when we do reader.GetValue(ordinalId).ToValueOrDefault<string>, within that method it will check null and then convert using oracle datereader

public static T ValueOrDefault<T>(this XElement element, T defaultValue = default(T))
        {
            if (element == null)
            {
                return defaultValue;
            }

            return element.Value.To(defaultValue);
        }

Open in new window

0
I think the answer to this is "yes" but I want to double check.

I'm working on code from 2002. It's .Net Frameowork 4.0. This is Windows Forms. We have to install the application on client machines manually...one by one.

I changed the Framework to 4.6.1. Compiled and all is good.

My manager says we can't deploy/install the upgrade on client's environments without installing  Framework 4.6.1 on client machines.

Do we need to install 4.6.1 n client machines?
0
I am writing a program to download images from a web page.  I am able to download the images, but I would also like to log the full path of where it came from.

Below is the code that I have written.

            WebBrowser scrapeWebBrowser = new WebBrowser();

            scrapeWebBrowser.Navigate("http://yahoo.com");

            HTMLDocument objHtmlDocument = (HTMLDocument)scrapeWebBrowser.Document;

            foreach (HTMLImgClass imageElement in objHtmlDocument.images)
            {
                //HTMLImage
                WebClient client = new WebClient();
                string fileName = System.IO.Path.GetFileName(imageElement.href);
                client.DownloadFileAsync(new Uri(imageElement.href), System.IO.Path.Combine(@"L:\temp\imagedownload\", fileName));

                //How do I get the full url for imageElement?
            }

Open in new window


Is it possible to return the full URL from my declared variable imageElement?
0
I am creating windows services using C# , and configurator for the service using windows form app in C#. So, I want to include start, stop and know the state of the service( Running/Stopped) functionality on my configurator, how would I do this using C# ? So if I click start button it is going to start the service and if I click the Stop button it would stop the service, and text field should display the status of the service (running, or stopped).

 All I want to make my configurator user friendly, so that user don't have to go to Task Manger and manually stop or start the service. Not only for the service I created, but this would allow me to write any service name on the text field, and should give me service status, and if it is already running, and  I click stop button it should stop, if it is stopped, and I click start button it should run.
0
Hi,

How can I make a string from database as a link?

<asp:HyperLink ID="SponsorWebsiteURL" NavigateUrl="XXXXX" runat="server">link</asp:HyperLink>

This is what I use in the page, what is the code to use in code-behind? thank you very much
0
I am trying to write a program using C# and WPF to download all images from a web page.

In my XAML I added the following control:

<WebBrowser x:Name="scrapeWebBrowser" Grid.Column="1" Grid.Row="1"/>

Open in new window


For testing, I created a test button that does the following:

scrapeWebBrowser.Navigate("http://yahoo.com");
HTMLDocument objHtmlDocument = (HTMLDocument)scrapeWebBrowser.Document;

foreach (IHTMLElementCollection imageElements in objHtmlDocument.images)
{
//I am not sure what to do here.  I am trying to get the reference to the image.
}

Open in new window


How do I get a reference in my code above?  Once I have the reference, how do I download it?

Any direction would be greatly appreciated.      

Many Thanks!
0
Why does this code deadlock?

I created a simple WPF project with a single button, and this is the button click code.

If I comment out the SetSynchronizationContext then it works. (Which brings up another question, why doesn't it crash complaining I'm not on a STA thread for the second MessageBox, because after the await it resumes on a different thread.)

With the SetSynchronizationContext line, it seems to deadlock at the await statement, I'm guessing it's unable to resume on the same thread it started on. Is there a hidden .Join() or .Wait() somewhere blocking the thread it started on? Is the thread it started on blocked somehow? (Or is it gone?)

private void Button_Click(object sender, RoutedEventArgs e)
{
    // Create a thread
    Thread newWindowThread = new Thread(new ThreadStart(async () =>
    {
        MessageBox.Show("Initial ThreadId=" + Thread.CurrentThread.ManagedThreadId.ToString());
        SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());
        await DoAsync();
        MessageBox.Show("Now ThreadId2=" + Thread.CurrentThread.ManagedThreadId.ToString());
    }));
    newWindowThread.SetApartmentState(ApartmentState.STA);
    newWindowThread.IsBackground = true;
    newWindowThread.Start();
}

private async Task DoAsync()
{
    await Task.Delay(1000);
}

Open in new window

0
HttpContext.Current is null after calling ConfigureAwait(false) in ASP.NET MVC using C#.  How do I resolve this problem.?

Please provide code fix.

Many thanks in advance.
0
C#.MVC What Controller for MP3 Upload Web Service?

I need a web service that accepts an MP3 file and kicks off a series of steps. So, what is the best type of Controller object to use?

And what kinds of configurations will be best for this? Does this require configurations available only through WCF?

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