Quantcast
Channel: Visual C# forum
Viewing all 31927 articles
Browse latest View live

Which piece of code is better optimised?

$
0
0

This is possibly the most perfectionist question I've ever asked but which of these two code pieces is better optimised?  I'd like to think it's the second one because I'm not assigning the value to another variable but I'm guessing you'd use the first if you wanted to debug before placing the value in the label?

string strUrlHost = Request.Url.Host.ToString();
lblURLHost.Text = strUrlHost;

Or

lblURLHost.Text = Request.Url.Host.ToString();




Azure Face API Eyes Occlusion Problems

$
0
0
Goodmorning,
I am using Microsoft.Azure.CognitiveServices.Vision.Face API sdk version for detecting faces for submitted images.
I have noticed strange behaviors on the faces with an occluded eye (for example a tuft on an eye, a hand on an eye, etc.). 
In these cases, the Face.FaceAttributes.Occlusion.EyeOccluded attribute is false, while hypothetically it should be true.
Could I have an explanation about this case?

How to handle or debug controls to control the values on closing the window forms

$
0
0
protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
Here, When i step into the below line (basically F11)
                components.Dispose();
I could see the value of "testComboBoxCtrl" got changed with immediate effect - which i want to debug and understand. Please recommend the ways if there are any.   
Infragistics.Win.UltraWinEditors.UltraComboEditor testComboBoxCtrl;


SomaSundaram R

How to assign any number of parameter keys on function Getbyid Repository pattern ?

$
0
0

Problem

How to assign any number of parameter keys on function Getbyid Repository pattern ?

I work on web app using repository pattern generics 

in  repository interface getbyid function as following

public T GetById(int Id)
        {
            return dbSet.Find(Id);
        }

and in interface Igenerics

T GetById(int Id)

suppose i dont know how many parameters passing so that what i do and how to call it please 

getbyid return keys for model may be keys for model 1key or 2 or 3 or 4 etc ..

so that can you help me using dynamic datatype or  params object[] keyValues

public T GetById(what i write here)
        {
            return dbSet.Find(Id);
        }
and in interface Igenerics

T GetById(what i write here)
when call getbyid how to call it
i need to use dynamic and params object[] keyValues


At which senerio race condition occur ?

$
0
0
At which senerio race condition occur ? Demonstrate with example.

The type or namespace name 'Android' does not exist in the namespace 'Xamarin.Forms.Platform'

$
0
0

Hi guys.
I Updated my nuget packages few days ago to new versions.
but my Android project has 2 errors in MainActivity.cs:
1:
The type or namespace name 'Android' does not exist in the namespace 'Xamarin.Forms.Platform' (are you missing an assembly reference?) Sama.SamaApp.Android MainActivity.cs

2:
'MainActivity.OnCreate(Bundle)': no suitable method found to override MainActivity.cs

i search it in google and find solutions.

But i tested all solutions in two up links but not worked for me.
i tested clear nuget and dotnet caches . removing bin & obj folders . restore nuget packages . remove and reinstall Xamarin.Forms .finally clean rebuilding the solution.
But I could not fix it.
thanks...

Differnece between boxing and unboxing in C#?

$
0
0
Differnece between boxing and unboxing in C#?Explain with example.

Use a Pascal library in C#

$
0
0

Hi,

I have a verry little dll writen with Pascal as a test to see how to use it with c#.

the dll:

library Dll_test;

{$mode objfpc}{$H+}

uses
  Classes
  { you can add units after this };

function Proc_Totaal :pchar; stdcall; export;
begin
  result := PChar('Test');
end;

exports
  Proc_Totaal;

{$R *.res}

begin
end.  

In C# i have:

using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace DllTest
{
    public partial class Form1 : Form
    {
        //const string SimpLibName = "Dll_test.dll";

        public Form1()
        {
            InitializeComponent();
        }

        [DllImport("Dll_test.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
        public static extern string Proc_Totaal();

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = Proc_Totaal();
        }
    }
}

When i click the button i get an error. This is:

Attempt to load a program with an incorrect format. (Exception of HRESULT: 0x8007000B)

What is wrong? Or where can i find a tutorial for loading pascal dll's?


How to send Strings via Bluetooth

$
0
0
How to send a string from Bluetooth ? I want to send some text commands to an Arduino. 

SSIS Package or CLR Function

$
0
0

We have a table which contains the basic data of our customers (e.g., First Name, Last Name, Identity Code and so fourth). The table has approximately 100,000 rows.

Now, we need to call several web services to get some data for each customer and then insert the received data from web services into some other tables in the database.

I'm considering two approaches to accomplish this task:

  1. Declaring several table-valued CLR functions and call web services through some .Net managed code, and then use these CLR functions in several stored procedures to insert the received data into several tables.

  2. The second approach which I'm considering is using an SSIS Package. For example, I can create some Script Tasks inside the SSIS Package and call web services, and then insert the received data into some tables through ADO.Net or some other providers.

Which approach is the best from your opinion? and why?

Processing 180 by 180 array of doubles

$
0
0

What is the optimum way in c sharp to process or parse an 180 by 180 array of double into memory. In a nutshell someone is passing me 180by180 array from Matlab and and I need to parse into memory using c sharp. Do I really need 2-dimensional array to this? Can someone point me in the right direction of process an 180by180 array. This is the code I have below.

MULTIPLIER = (Math.PI * 2);

double azmiuthLength = (MULTIPLIER * azmiuth); double elevationLength = (MULTIPLIER * elevation); for (double x = 0; x < Math.PI; x += Math.PI / 180)

{ double xAxis = Math.abs(Math.sin( azmiuthLength * Math.cos(x) / azmiuthLength * Math.cos(x))); this.antennaPattern.getRadiationArray2D()[xIndex][0] = xAxis; int yIndex = 0; for (double y = 0; y < Math.PI; y += Math.PI / 180)

{ double yAxis = Math.abs(Math.sin(elevationLength * Math.cos(y) / elevationLength * Math.cos(y))); antennaPattern.getRadiationArray2D()[xIndex][yIndex] = yAxis; yIndex++; } xIndex++; }



pianoboyCoder

Windows Service doesn't execute OnStart()

$
0
0
     

I have a windows service that is having trouble executing the Onstart() method after installing it and running it from the service menu.I'm logging everything that is happening at every step of the execution to see where the problem is. But there is no error, it logs and runs fine in the main method , up until the service is actually called to run and then it just does nothing.

It's interesting to note that it doesn't have ANY problem running in debug.

My program class(starting point) from which the service is called : 

using System;
using System.Configuration;
using SimpleInjector;
using System.ServiceProcess;
using Microsoft.Extensions.Logging;
using SimpleInjector.Lifestyles;
using SmsHandler.Domain;
using SmsHandler.Interfaces;
using SmsHandler.Interfaces.Configuration;
using SmsHandler.SimpleInjector;

namespace SmsHandler.Sender
{
    public class Program
    {
        private static Container _container;
        private static ILogger<Program> _logger;
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        private static void Main()
        {
            _container = SimpleInjectorContainer.Build(registerConfig: true, useThreadScopedLifestyle: true);
            SimpleInjectorContainer.LoggAndVerify(_container);

            using (ThreadScopedLifestyle.BeginScope(_container))
            {
                try
                {
                    _logger = _container.GetInstance<ILogger<Program>>();
                    _logger.LogInformation("Test - Works");
                    VerifyConfiguration();
                }
                catch (Exception ex)
                {
                    var logger = _container.GetInstance<ILogger<Program>>();
                    logger.LogError(ex, "Configuration is not valid");
                    throw;
                }

                if (Environment.UserInteractive)
                {
                    RunDebug();
                }
                else
                {
                    System.Diagnostics.Debugger.Launch();
                    _logger.LogInformation("It's Here 49");
                    ServiceBase[] ServicesToRun;
                    ServicesToRun = new ServiceBase[]
                    {
                        _container.GetInstance<SenderService>()
                    };
                    _logger.LogInformation(_container.GetInstance<SenderService>().GetType().ToString());
                    //_logger.LogInformation("It's Here 56");
                    ServiceBase.Run(ServicesToRun);
                    _logger.LogInformation("It's Here 58");
                }
            }
        }

        private static void RunDebug()
        {
            var senderService = _container.GetInstance<SenderService>();
            senderService.TestStart();
            Console.WriteLine("Sender Started Debug");
            Console.ReadLine();
            senderService.TestStop();
        }
        private static void VerifyConfiguration()
        {
            var configValidator = _container.GetInstance<IConfigurationValidator>();
            configValidator.VerifyOperatorPrefixNumbers();
            configValidator.VerifyConfiguration();
            configValidator.VerifyOperators();
            //configValidator.VerifyOperatorMaxSmsCheckCount();

            // TODO: Check Operator attributes except Unknown
        }
    }

}
   




My actual service : 

using System;
using System.ServiceProcess;
using System.Threading;
using Microsoft.Extensions.Logging;
using SimpleInjector;
using SimpleInjector.Lifestyles;
using SmsHandler.Interfaces;
using SmsHandler.Interfaces.Configuration;

namespace SmsHandler.Sender
{
    public partial class SenderService : ServiceBase
    {
        private readonly Container container;
        private readonly ILogger<SenderService> logger;
        private readonly ISmsHandlerConfig config;
        private readonly IConfigurationValidator configValidator;

        public SenderService(
            Container container,
            ILogger<SenderService> logger,
            ISmsHandlerConfig config,
            IConfigurationValidator configValidator)
        {
            this.InitializeComponent();
            this.container = container;
            this.logger = logger;
            this.config = config;
            this.configValidator = configValidator;
        }

        public void TestStart()
        {
            Console.WriteLine($"Starting {ServiceName} service");
            this.OnStart();
        }

        public void TestStop()
        {
            Console.WriteLine($"Stopping {ServiceName} service");
            this.OnStop();
        }

        protected void OnStart()
        {
            try
            {
                this.logger.LogInformation($"{this.ServiceName} starting");
                SmsHandlerAction();
            }
            catch (Exception ex)
            {
                this.logger.LogError(ex, $"Error starting service {this.ServiceName}");
                throw;
            }
        }

        protected override void OnStop()
        {
            try
            {
                this.Dispose();
                this.logger.LogInformation($"{this.ServiceName} stopped");
            }
            catch (Exception ex)
            {
                this.logger.LogError(ex, $"Error stopping service {this.ServiceName}");
            }
        }

        private void SmsHandlerAction()
        {
            while (true)
            {
                this.logger.LogInformation($"{this.ServiceName} started");
                using (ThreadScopedLifestyle.BeginScope(this.container))
                {
                    var smsSenderService = this.container.GetInstance<ISmsSenderService>();
                    var sendResult = smsSenderService.SendSms(this.container);

                    // Wait if there are not messages for sending
                    if (!sendResult && this.config.IdleTimeMiliseconds != 0)
                    {
                        Thread.Sleep(this.config.IdleTimeMiliseconds);
                    }
                }
            }
        }
    }
}


this is what is logged:

> 2019-02-12 18:02:18.7972 INFO Test - Works

> 2019-02-12 18:02:20.6370 INFO It's Here 49

> 2019-02-12 18:02:20.6410 INFO It's Here 56

and after I stop the service :

> 2019-02-12 18:02:35.7375 INFO SenderService stopped

> 2019-02-12 18:02:35.7375 INFO It's Here 58

It missing the `this.logger.LogInformation($"{this.ServiceName} starting");` part.

It doesn't log the line in the onstart method , because it never actually executes, I checked if the service was running, but just failed to log and that is not the case.    

My IDE is VS 2017, OS is Win 7, DI library is SimpleInjector 4.0.12.

I know about a similar question asked on here(cant link it currently, Ill post it at the bottom as text) but I don't see how it solves my problem.

I'm pretty lost so any guidance will be of help.

The other question :

social.msdn.microsoft.com/Forums/vstudio/en-US/b8c8638c-49bf-4f77-a4eb-ad1af0c8d0f5/windows-service-doesnt-execute-onstart?forum=csharpgeneral

Proplem with c# and pnputil

$
0
0

Hello

I have the problem that i cant call the pnputil function over c#.

My code:

static void ExecuteCommand(string command)
        {
            int exitCode;
            ProcessStartInfo processInfo;
            Process process;

            processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
            processInfo.CreateNoWindow = true;
            processInfo.UseShellExecute = false;
            // *** Redirect the output ***
            processInfo.RedirectStandardError = true;
            processInfo.RedirectStandardOutput = true;

            process = Process.Start(processInfo);
            process.WaitForExit();

            // *** Read the streams ***
            // Warning: This approach can lead to deadlocks, see Edit #2
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();

            exitCode = process.ExitCode;

            Console.WriteLine("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
            Console.WriteLine("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
            Console.WriteLine("ExitCode: " + exitCode.ToString(), "ExecuteCommand");
            process.Close();
        }
ExecuteCommand("pnputil /add-driver " + inffilepath);

Result:

output>>(none)
error>>Der Befehl "pnputil" ist entweder falsch geschrieben oder
konnte nicht gefunden werden.

ExitCode: 1

Error in eglish: 

The command "pnputil" is either misspelled or
could not be found.

I use Windows 10 and .NET Framework 4.6.1

I i start cmd and type the command it is working.

I dont find the problem.

Can someone help me?

Thanks


How do I put sections of txt file to seperate varibles?

$
0
0

So I have a txt file with several sections and I want to put those sections into diffrent variables.

For exapmple here is my text file:

Section1:
item1

Section2:
item2
item3
item4

so I want to put all item from section1 to a varibale and to put all items from section2 to its own variable


How could you make 3d models spin and do this in the correct orientation Any advice on how this could be done.

$
0
0

I need to use C# and Xaml in visual studio. Anyone know how this would be possible.


Pass selected text with F9 or another function key from any application to C# application

$
0
0

Hi,

I would like to program a phone dialer to select a phone number in any application, and with a keypress, F9 for example, pass it to a little C# application. The application interfaces with the PBX to automaticly dial the number for the user. 

What solution can i use to pass a selected text from any application to the C# application?

Twan.

how to look up a user by email in AD

$
0
0

Hi,

I have a condition for few users where the mail address is misspelt in the front end application due to which i see a mismatch when i try to send email to these users,I get exception.

How to check if a user is existing in the AD by looking up his email?

I started doing the below,but then unfortunately realized that the I couldnt search by email as IdentityType allows only few properties from the AD.

public bool CheckUserExist(string Mail)
        {
            using (var domainContext = new PrincipalContext(ContextType.Domain, "abc", "xyz1234", "test"))
            {
                using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, ?))
                {
                    return foundUser!=null;
                }
            }
        }

walking thru a network of nodes in c#

$
0
0

Hi. I'd like to model a 40-50 node network in my db on a single sql server table.  And use c# to walk thru the network triggering work on a separate thread for each node that is enabled.

Each node would have 1-n predecessor nodes.  Every time work is completed on a thread, c# would check the network for new nodes that can be triggered based on the fact that a completed work status for Node X has just been returned.

I can handle the network (schedule) model in the db table.  And marking node "completed" flags to help this algorithm along.

I'd like some advice on the rest of it.  I see an article and example at https://www.codeproject.com/Articles/18976/A-simple-Binary-Search-Tree-written-in-C but suspect that a binary search tree is not what I am describing because I can have more than one predecessor for any node.  The oval (coming off d,f,g,h) in the diagram is what I call a phantom.  I may have phantoms in my model as a convenient way of not repeating more complicated predecessor groups of nodes.  

Does the community know of an example I can look at?  I am just a novice with c#.  I've pasted an image of a very simplified network example below.  Maybe I can hydrate a known class from the table and borrow some examples out there that walk such a class?


File Permissions Issue while compiling....?

$
0
0

I have downloaded a solution file with three projects from TFS.

This is my first crack at compiling the code after I have set up all the 'References".

The errors I am getting suggest that I need to set the permissions on the AppData or the Temp folder.

I think I might need some help on how to do this on the command line since, when I click to open the File Explorer, I do not see an option to run it as Admin.  How do I do that?

Here is the sample of the errors I am getting.  Please advise...

ErrorAn error has occurred during compilation. c:\Users\...\AppData\Local\Temp\sd22o3dh\sd22o3dh.0.cs(101,13) : warning CS0162: Unreachable code detected

ErrorAn error has occurred during compilation. error CS1583: 'c:\Users\...\AppData\Local\Temp\sd22o3dh\CSC4522B3A7C0D144688CC27DF8927708.TMP' is not a valid Win32 resource file

ErrorAn error has occurred during compilation. error CVT1101: cannot open 'c:\Users\...\AppData\Local\Temp\sd22o3dh\CSC4522B3A7C0D144688CC27DF8927708.TMP' for reading

ErrorThe source file for this compilation can be found at: "C:\Users\...\AppData\Local\Temp\4f696efb-a270-420e-b197-c8264416dcc9.txt"

ErrorThe task factory "CodeTaskFactory" could not be loaded from the assembly "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Build.Tasks.Core.dll". The task factory must return a value for the "TaskType" property.

ErrorAn error has occurred during compilation. c:\Users\...\AppData\Local\Temp\f3ldnp4h\f3ldnp4h.0.cs(121,13) : warning CS0162: Unreachable code detected

How to write to multiple serial ports at the same time

$
0
0

Hi,

I am creating an application that sends out data to multiple serial ports(Arduino nano's). Speed plays a pretty big role in this project, so it isn't an option to write to all the serial ports one after the other.

I am using "Write (Byte[], Int32, Int32)" to send the data to the serial ports and it is quick enough when it only has to send the data to a single serial port, but when it has to write the data to multiple serial ports it takes way longer, because it writes the data to the serial ports one after the other.

So is there a way that I could write to multiple serial ports at the same time?

Viewing all 31927 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>