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

Hello Experts,
I am working with Visual c# and windows 10.
I need to show a circle (200 pixels diameter) somewhere in the form.
The circle can be dragged and change position inside the form:

Up until here, I am ok, can do it...

Now the circle has to be divided into four equal parts,
Each part different color.
Each part has to perform a different task when clicked or right click
nad if outside the circle the same event does nothing.

So far I can do everything with rectangles since PictureBox is like that
But how can I have objects with a different form than a rectangle?
Or any ideas on how to do the last with the actual tools?

Regards,
0
I'm thinking I need a lookaround expression for this but the exact syntax is escaping me. I need a Regular Expression that will match on the word "then" but only once and only if the word "else" doesn't come before it. I'm using it for syntax highlighting and I want to make sure it highlights correctly for one and only one case. For example:

if (condition) then "something" else "something else"

Open in new window

should be 100% valid but

if (condition) else "something else" then "something"

Open in new window

should definitely fail

Things should also fail if the word "then" appears more than once unless that word is enclosed in double quotes. That one is probably a bit tricky.
0
How can the type be se in runtime in C#?

      public object Test(int whatType)
      {
         dynamic ret;
         if whatType = 1
         {
            T = blabla;
         }
         else
         {
            T = somethingelse;
         }

         ret = GetData<T>()
         return ret;
      }

Open in new window


Here I want to set T to a class to use it in GetData. This must be decided in runtime.
0
I have a website running on a Windows 2019 Server in IIS, using asp.net and C#.

When the user goes to my site, I want to immediately redirect them to my new site. I don't need to mask the URL. It's perfectly fine to have the new URL appear in the browser bar. The new site uses https so I don't want the redirect to attempt to mask or otherwise cause the browser to display a warning that the site is not secure.

I know there are various ways to redirect one web page to another - through html, javascript and even in asp.net.

Can anyone share a sample code that can give the fastest, most reliable redirect?

If I try to handle the redirect using JUST html:

<!DOCTYPE html>
<html>
   <head>
      <title>My Site</title>
      <meta http-equiv = "refresh" content = "0; url = https://mynewwebsite.com" />
   </head>
   <body>
      <p>Welcome to My New Site</p>
   </body>
</html>

Open in new window


...even when I set the time to 0, the user still (briefly) sees this placeholder page until it finally redirects. I don't like that.

I thought about doing it using JavaScript but what if the user has JS disabled?

So then I thought maybe it should be handled in asp.net but I guess that would require a round trip to the server. Not the end of the world but ... maybe a COMBINATION of these techniques starting with the fastest method and then using something as a fallback?

(Note: I know I can also handle this redirect on the web server, but I don't want to redirect ALL instances of my old domain. Only the home page)
0
Looking to implement possible actions after login such as:

MFA
Change Password
Accept License Agreement
Watch an AD

After a user has validated their credentials, multiple actions may need to be executed before they can use the app. What would be the best way to design this? Keep in mind that they all need to happen in a specific  order and they each need to know that the action before it succeeded.  So if a user logs in and the password expired, they would need a screen to change their password and then they would need to accept an agreement.

If you have any questions please let me know.
0
I have a MVC 5 .net 4.7.2 identity website. this works well. i want to generate a password reset token from a separate WinForms (4.5.2) application. (UserManager.GeneratePasswordResetTokenAsync)..

As far as I can tell I need to reference Microsoft.Owin.Security.DataProtection and Microsoft.AspNet.Identity.Owin.. I am having trouble creating a UserManager object.
I'm struggling with the minimum requirements WinForms needs to make this... it seems like the entityframework is required or something.

Ideally I would like to call the ResetPassword action from the WinForms project, but I figure if I can run the GeneratePasswordResetTokenAsync method then I can create and send the email from code with my own method.. getting the userid is no problem, as i know how to access the database etc...

I realise the above is fairly vague, but hopefully enough information to provide advise. thanks.
0
Hello,

I've one Serilog file for my application and i'd like to create a button like "Open Log" and would like to read real time log file there, but i don't have experience how is it possible to do that?

Anyhelp would be great.

Thank you.
0
I have a framework 4.8 C# project (project Test) which includes a NetStandard 2.0 project (the project, not just the dll, project Library) in the solution.

The dependencies seems to be picked up by the Test project, but the dependency files are not copied to the bin output directory, so during run in IDE there is an error when it tries to use of the dependencies from Library (file not found).

How can this be fixed ? I'm using PackageReference in both projects. Just to get it working I had to add all dependencies from Library to Test manually.
0
Hello,

I've a menu in my MainWindow and both of them have seperate ViewModels MainWindowViewModel and MainMenuItemViewModel. It works without problem but in designer it underlined with blue color and it says "Cannot Resolve Property"

000538.jpg

And my code is like below;

               <Menu IsMainMenu="True" ItemsSource="{Binding MainMenuItemViewModel.MainMenuItems}" Grid.Column="0">
                    <Menu.Resources>
                        <Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource MaterialDesignMenuItem}">
                            <Setter Property="Header" Value="{Binding Path=DisplayName}"/>
                            <Setter Property="Command" Value="{Binding Path=MainMenuItemCommand}"/>
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding Path=IsSeparator}" Value="true">
                                    <Setter Property="MenuItem.Template">
                                        <Setter.Value>
                                            <ControlTemplate TargetType="{x:Type MenuItem}">
                                                <Separator Style="{DynamicResource {x:Static MenuItem.SeparatorStyleKey}}"/>
                                            </ControlTemplate>
                                        </Setter.Value>
                                    </Setter>
                                </DataTrigger>
                            

Open in new window

0
How to create .xlsx file in c#, .net?
0
I have to create a web form for 100 products and services that we have and each one has similar steps. We use Mvc 4 with c#. It has some simple workflow as well. And they will be saved into the database

Any suggestions how to get start?
0
Hello,

I have ViewModel like below but it doesnt update progressbar visibility and Indeterminate values.

Where's the problem i couldnt find. Any help would be grateful.

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows;
using System.Windows.Input;
using MyTool.Core;
using MyTool.QCheck.Outputs;

namespace MyTool.ViewModels.ToolBox.ToolBoxButton.Check
{
    public class BodyLoadsViewModel : BindableBase
    {
        public ICommand RunCommand { get; private set; }

        private BackgroundWorker worker;

        public ICommand StartCommand { get; private set; }
  
        private int progress;
        public int Progress
        {
            get => progress;
            set => SetProperty(ref progress, value);
        }


        private int myValue;
        public int MyValue
        {
            get => myValue;
            set => SetProperty(ref myValue, value);
        }


        private bool includeDeformation;
        public bool IncludeDeformation
        {
            get => includeDeformation;
            set => SetProperty(ref includeDeformation, value);
        }
        private bool progressIsIndeterminate;
        public bool ProgressIsIndeterminate
        {
            get => progressIsIndeterminate;
            set => SetProperty(ref progressIsIndeterminate, value);
        }
        private Visibility progressIsVisible;
        public Visibility ProgressIsVisible
        {
            get => 

Open in new window

0
I have used C# trying ti make a program for observing stocks.
I see there are many ways of getting stock info from their symbols.

I have tried to scrape finance.yahoo to get all stock names and symbols. But this is slow and also for the US Markets it does not provide more than 10.000 stocks ( out of apx 14000.  Some months ago I informer Yahoo about this but they do not seem interested in fixing it.

My question is if anyone has a way of getting stock names and symbols for different countries.

Regards
Haakon Bruusgaard
0
I am getting String was not recognize as valid DateTime when I try to upload to the database.  Any Ideas see code below..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Security.Principal;
 
namespace CertificationCapture {
    public partial class _Default : System.Web.UI.Page {
        protected void Page_Load(object sender, EventArgs e) {
            if (!IsPostBack)
            {
                Cal1.Visible = false;
                Cal_exp.Visible = false;
            }
        }
 
 
        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            if (Cal1.Visible = false)
            {
                Cal1.Visible = true;
            }
            else
            {
                Cal1.Visible = true;
            }
        }
 
        protected void Cal1_SelectionChanged(object sender, EventArgs e)
        {
            ent_date.Text = Convert.ToString(Cal1.SelectedDate.ToString());
            Cal1.Visible = false;
        }
 
        protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
        {
            if (Cal_exp.Visible = false)
            {
                Cal_exp.Visible = true;
            }
            else
            {
                Cal_exp.Visible = true;
            }
 
        }
 
        protected void …
0
Hello EE Community,

I have been struggling trying to figure out how the heck to impersonate via .Net Core API  sending a HttpWebRequest as the Windows Identity user.   I have tried forum articles out there and posting what I tried last but this does not work.   It works fine when I run via IIS Express I have Windows Authentication and Anonymous on that I need for now.   When I run via IIS Express the "DefaultCredentials" are picking up my credentials but when I run deployed to IIS the Application Pool identity is using a service account which I understand but now I need to impersonate and with Core it seems so difficult.   This is what I am trying when deploying to IIS but it is not working and still picking up the app pool identity service account versus my Windows Identity essentially.   The Windows Identity has myself correct but the DefaultCredentials does not it uses the app pool.   I tried this via forum articles still no dice the CredentialCache.DefaultCredentials is still the app pool.  Needing help understanding how to handle this in Core.

  WindowsIdentity identity = (WindowsIdentity)_httpContextAccessor.HttpContext.User.Identity;
                WindowsIdentity.RunImpersonated(identity.AccessToken, () =>
                {
                    Uri theUri = new Uri(string.Concat(this.session.HostURL, "/refi/services"));
                    HttpWebRequest theHttpWebRequest = (HttpWebRequest)WebRequest.Create(theUri);
                    

Open in new window

0
How to write Data to Excel Sheet (.xlsx) from DataTable dynamically in SSIS using SCript Task and C#?

I am getting the data from SQL Server and trying to insert that data in Excel Sheet. One of the column contains long text with ' in the string. I feel when string contains ' then its having issues and it's failing to  insert into excel sheet. Failing while  Excel_OLE_Cmd.ExecuteNonQuery(); and it says Missing operator in the query expression.

Excel_OLE_Cmd.CommandText = command;
I am getting the command while debugging

"Insert into Sheet1([ID],[Name],[Message],[Date],[Category])Values('123','test','After time Form\r\n:\r\n\r\nDescribe:This is it's history book.','11/14/2019','Development')"

Problem is in Message column. This field contains lots of text with quotes. I am not sure how to fix in the code that I wrote. Please fix my code.
code.docx
0
Because, the comvisible did not work, I would like to make a c++ wrapper, to call my c# dll functions.
0
Can you assist me on this one, I  am trying to  calculate this in C# and I ave so much trouble.  I have posted the instructions below.

Instructions
Design and implement control structures in C # that facilitate decision making. You will create a Windows form that processes student’s grades.
Requirements
1. The form should have appropriate controls to obtain from the user values for the following grade components:
• Three quizzes,
• Midterm, and
• Final exam.
2. Each grade is a value from 0 to 100. For now, you may assume that user enters data correctly.
3. The grading scheme is as follows:
a. The lowest of the three quiz marks is dropped.
b. The remaining two quizzes account for 30% of the course grade (15% each).
c. The midterm makes 30% of the course grade, and the final exam accounts for 40%.
2. Your application should calculate and display:
a. The course grade as a value from 0 to 100, with no more than two decimal digits.
b. The letter grade, which is calculated as follows:
• Course grade 90 or more results in A
• Course grade that is 80 or more, but less than 90 is B
• Course grade that is 70 or more, but less than 80 is C
• Course grade that is 60 or more, but less than 70 is D
• Course grade below 60 is F
2. Also, your application should indicate which of the three quizzes is dropped, either referring to it by number or by value of the dropped quiz.
3. Calculation is triggered by a Calculate button.
0
Can you please help me read or understand this piece of code.  I am new in C# and I have to document it.  So I need your assistance.
Thank you.
0
Having the following very simple Xaml:
<Window x:Class="WPF_Tests.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF_Tests"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800"
        WindowStyle="None"
        AllowsTransparency="True">
    <Window.Background>
        <SolidColorBrush Opacity="0.5" Color="Black"/>
    </Window.Background>
    <Grid>
        <Button HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,10,10,0">
            Close
        </Button>
        <TextBlock x:Name="textBlock" HorizontalAlignment="Center" VerticalAlignment="Center" TextWrapping="Wrap" Foreground="White" FontSize="36">
            This is a sample message
        </TextBlock>
    </Grid>
</Window>

Open in new window

How do I make it such that all mouse events are passed through the window except for when in the button control? I want to be able to not only see through the window but click through it as well but still have a way of closing the window by clicking on the button.
0
I use the following codes in aspx web application.
It takes excel file and then insert a record to the database.
The code is working until it reaches 12,000 records.

We verify the webconfig and excel file itself and do not have any issues.

We use window server2012



https://www.experts-exchange.com/askQuestion.jsp#

Open in new window


 public static void UploadFile(ref System.IO.Stream fileStream)
    {
        string aidString = HttpContext.Current.Session[ezGlobals.id].ToString();

        string shortDateString = DateTime.Now.ToShortDateString().Replace("/", "");
        string hourString = DateTime.Now.Hour.ToString();
        string minuteString = DateTime.Now.Minute.ToString();
        string secondString = DateTime.Now.Second.ToString();

        string pathPrefix = "~/Staff/Portal/Home/Files/";
        string pathPostfix = ".xls";

        string path = HttpContext.Current.Server.MapPath(pathPrefix + aidString + shortDateString + hourString + minuteString + secondString + pathPostfix);

        var newFileStream = File.Create(path);
        fileStream.Seek(0, SeekOrigin.Begin);
        fileStream.CopyTo(newFileStream);
        newFileStream.Close();

        fileStream.Seek(0, SeekOrigin.Begin);

        var doc = new HtmlDocument();
        doc.Load(fileStream);
        var nodes = doc.DocumentNode.SelectNodes("//table/tr");
        DataTable table = new DataTable("MyTable");

        var headers = nodes[0]
            .Elements("th")
            

Open in new window

0
Hi,

In WPF .Net Core how can I have a listview / listbox (I am guessing) with a HTML Image and a check box.

So something like this (excuse the Text Graphics)

+------------------------------------+
|                                                            |
| x CheckBox Title 1                           |
|                                                             |
|                                                           |
|                                                           |
| HTML Image 1                                  |
|                                                           |
+------------------------------------+
|                                                            |
| x CheckBox Title 2                           |
|                                                             |
|                                                             |
|                                                              |
| HTML Image 2                                  |
|                                                             |
+------------------------------------+
.
.
. And so on

Basically so when I select each checkbox in my code I can tell that I have selected this particular Item?

In the example above there would be two items.

So I am looking for some sample code that explains how I can do this?

Thanks,

Ward.
0
Hello,

I have a text file like below;

!file.version = 1.0!

!**********************************************************************
!Perform Summary
!**********************************************************************

$START
	Center of Gravity / UniqueText1= *CHANGE TEXT IF IT'S EXIST IN HERE*
	Mass Property / UniqueText2= *WRITE TEXT TO HERE*
$END

$UNKOWNS

Open in new window


I'd like to write some values on the right side of "=" symbol where my UniqueText's exist it should only search between $START and $END tags and only look for UniqueTexts.

I mean it will look for  "UniqueText1"  and find it in line which writes "Center of Gravity / UniqueText1"

now i'd like to write my text right side of equation symbol.

Any help would be greatful.

Thank you.
0
Hello,

I am looking for the equivalent in VB.NET (or in C #) of the following PHP code

$params = array(
  'http'=>array(
    'method'=>"POST",
    'header'=>"content-encoding: amz-1.0 ....Signature=1c1b2f3c38bac12904cf84",
    'content' =>"example")
);
$stream = stream_context_create ( $params );

$fp = @fopen ( 'http://www.example.com, 'rb', false, $stream );

$response = @stream_get_contents ( $fp );
0
Hello,

I'd like access one of the parameter from my COM interface class with below code;

simpackcomslvLib.ScrTypeVarParameter par = prim.par(index[0], index[1], index[2], index[3], index[4], index[5], index[6], index[7], index[8]);
Console.WriteLine(par.val);

Open in new window



if it's existing with that indexes it gives result but if there's no parameter at given indexes it throws TargetInvocationException. I'd like to avoid that throw but didn't succeeded it. I tried to check if par == null but it's always not null it always shows System.__ComObject and if i tried to check par.val it throws that TargetInvocationException, so how can i avoid if parameter doesnt exists at given index i'd like to pass and try new indexes but as i said it throws an error.
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).