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

ado mixed Data Force

$
0
0

Dear All,

i import data vom an excelfile via ADODB.Connection

    Set cn = New ADODB.Connection
    cn.Provider = "Microsoft.ACE.OLEDB.12.0"
    cn.ConnectionString = "Data Source=" & File & ";Extended Properties=""Excel 12.0;HDR=NO;IMEX=1"""

I put imex=1, because i have mixed data.

If the first cell in a column is a number, and the next eight cells are null (empty) and the ninth cell is a text, data is lost.

The connection drive obviosly decides that the columndata is in a numberformat and collects only numbers, all txt will be ignored.

if the seventh cell is text everything will be collected. 

How can i force the driver to overtake all data.

Oliver


Hi man

$
0
0

I just do what you write but i want generate 3 different words, how i can do it? 

Thanks <3

DataGridView bugs

$
0
0

Hi all,

How to prevent datagridview bugs , nad in which event i can handle it?

Thanks


Esmat

Specifying a range for a list input relative to previous list inputs

$
0
0

I'm trying to validate user input to a range which compares an input to previous inputs in a list, I can seem to find the syntax. I've written something indicative of what i'm trying to do, but the if statement that declares the range is obviously all wrong. My code reads as follows:

List<Opening> OpeningsList = new List<Opening>();

int MinRange = openingFromSOP + openingWidth + (int)StudCount() / 2 * (int)TimberThickness;
            if (openingFromSOP > MinRange.CompareTo(List<Opening> OpeningsList))
            {
                OpeningsList.Add(new Opening() { OpeningFromSOP = openingFromSOP - StudCount() / 2 * TimberThickness, DistanceOverOpening = openingFromSOP + openingWidth + StudCount() / 2 * TimberThickness, OpeningWidth = openingWidth + StudCount() * TimberThickness, OpeningHeadHeight = openingHeadHeight, OpeningCillHeight = openingCillHeight, LintelTicker = flag2 });
            }
            else
            {
                ContentDialog CillTooHigh = new ContentDialog
                {
                    Title = "Invalid input",
                    Content = "The opening is within the bounds of another opening.",
                    CloseButtonText = "Ok"
                };
            }

Any help would be appreciated, cheers, Matthew

Writing a very simple encryption tool for a login

$
0
0

Hello! I'm looking for a simple, easy, and very non-complicated way to encrypt a string.

Basically, I'm saving a 4-character PIN to an XML file and I'm wanting to just hide its true value while allowing a user to login using that PIN. Security is such a non-issue that I don't even have to encrypt the PIN, I'm just wanting to do it. So the easier the solution the better.

Imagine the user creates a PIN of '1234'. That PIN is saved in the XML file as <PIN>1234</PIN>.

When the user logs back in, I just need to be able to take their input and compare it against the value in <PIN>. If it matches, they're logged in.

Any recommendations?

Thanks!

UWP(Zoom out the Program can keep going on the background)

$
0
0

I have a windows 10 c# Universal Windows App and when zoom out the program,it also keep gooing.

what should i do?

 

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

usb communication using c#

$
0
0

hello, 

good morning

in my application i need to communicate with usb using c# in windows forms applications. how to send data to usb and how to receive data from usb

please help me

Thanks and Regards

Rajani B


How to get string output when converting a console application into a .dll?

$
0
0

hello,

I want to convert a console application to a .dll file,and get the result when load the dll,what I don't know is how to get the result in a dll file after converted.Below is the origin console code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation;
using System.Diagnostics;
using System.Net;
using System.Threading;
using System.Net.Sockets;

namespace ConsoleApplication1
{
    class Program
    {
        static CountdownEvent countdown;
        static int upCount = 0;
        static object lockObj = new object();
        const bool resolveNames = true;

        static void Main(string[] args)
        {
            countdown = new CountdownEvent(1);
            Stopwatch sw = new Stopwatch();
            sw.Start();
            string ipBase = "192.168.1.";
            for (int i = 1; i < 255; i++)
            {
                string ip = ipBase + i.ToString();

                Ping p = new Ping();
                p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted);
                countdown.AddCount();
                p.SendAsync(ip, 100, ip);
            }
            countdown.Signal();
            countdown.Wait();
            sw.Stop();
            TimeSpan span = new TimeSpan(sw.ElapsedTicks);
            Console.WriteLine("Took {0} milliseconds. {1} hosts active.", sw.ElapsedMilliseconds, upCount);
            Console.ReadLine();
        }

        static void p_PingCompleted(object sender, PingCompletedEventArgs e)
        {
            string ip = (string)e.UserState;
            if (e.Reply != null && e.Reply.Status == IPStatus.Success)
            {
                if (resolveNames)
                {
                    string name;
                    try
                    {
                        IPHostEntry hostEntry = Dns.GetHostEntry(ip);
                        name = hostEntry.HostName;
                    }
                    catch (SocketException ex)
                    {
                        name = "?";
                    }
                    Console.WriteLine("{0} ({1}) is up: ({2} ms)", ip, name, e.Reply.RoundtripTime);
                }
                else
                {
                    Console.WriteLine("{0} is up: ({1} ms)", ip, e.Reply.RoundtripTime);
                }
                lock (lockObj)
                {
                    upCount++;
                }
            }
            else if (e.Reply == null)
            {
                Console.WriteLine("Pinging {0} failed. (Null Reply object?)", ip);
            }
            countdown.Signal();
        }
    }
}

Posting data to a web form in C#

$
0
0

Trying to send data to a web form. It always replies "400".

I can do it from an html page like so:

<form action="https://api.particle.io/v1/devices/4500*****3036/Settings?access_token=hidingthispart" method="POST">
        Tell your device what to do!<br><br><input type="text" name="arg" value="" > The settings string.<br><input type="submit" value="Do it!"></form>

But not from .net code like so:

   string postData = "arg=" + tbMaxChamber.Text + "," + tbMinChamber.Text + "," + tbMeatTarget.Text + "," + tbMeatAlert.Text;
            string url = "https://api.particle.io/v1/devices/4500***********63036/Settings?access_token=hidingthispart";

            WebRequest request = WebRequest.Create(url);
            request.Method = "POST";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            WebResponse response = request.GetResponse();
            lblResponse.Text = (((HttpWebResponse)response).StatusDescription);

            dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            lblResults.Text = responseFromServer;
            reader.Close();
            dataStream.Close();
            response.Close();

Perhaps I have to do something different because it's an https?

Difference between async and await in c#?

$
0
0
Difference between async and await in c#?

Can I get some help to write an xml to binary

$
0
0

hello,

I am trying to create a binary dictionary file for a program.

The settings file is in xml, and I want the program to load the binary file.

here is the code of the xml:

<?xml version="1.0" encoding="utf-16"?><Lang Version="1.0" AppVersion="1.0.0.0"><Dialogs><Main><Menus><I Name="Main_Menu_Load">Load</I><I Name="Main_Menu_Save">Save</I><I Name="Main_Menu_Exit">Exit</I><I Name="Main_Menu_SaveAll">Save All</I><I Name="Main_Menu_Close">Close</I><I Name="Main_Menu_CloseAll">Close All</I><I Name="Main_Menu_Languages">Languages</I><I Name="Main_Menu_Help">Help</I><I Name="Main_Menu_Help_About">About</I><I Name="Main_Menu_Help_CheckForNewVersion">Check For New Version</I><I Name="Main_Text_LoadLanguage">Load Language {0}</I><I Name="Main_Menu_LoadMultiple">Load Multiple</I><I Name="Main_Menu_EmptyTextsColor">Empty Texts Color</I><I Name="Main_Menu_MatchingTextsColor">Matching Texts Color</I><I Name="Main_Menu_ExpandAll">Expand All</I><I Name="Main_Menu_CollapseAll">Collapse All</I><I Name="Main_Menu_ChangeColors">Change Colors</I></Menus><Headers><I Name="Main_HDR_Name">Name</I><I Name="Main_HDR_WarningName">Name</I><I Name="Main_HDR_WarningLanguages">Languages</I><I Name="Main_HDR_ErrorName">Name</I><I Name="Main_HDR_ErrorLanguage">Language</I></Headers><Texts><Logs><I Name="Main_Text_MissingFormatArgument">Missing format arguments : {0}</I></Logs><I Name="Main_Text_Warnings">{0} Warnings</I><I Name="Main_Text_Errors">{0} Errors</I></Texts></Main></Dialogs><Questions><I Name="Question_SaveChangesToFollowingLangs">Save changes to the following language(s) ?</I></Questions><Infos><I Name="Info_XmlSavedTo">'{0}' xml saved to {1}</I><I Name="Info_DicxSavedTo">'{0}' dicx saved to {1}</I><I Name="Info_LanguageAlreadyLoadedAt">'{0}' already loaded at {1}</I></Infos><Errors><I Name="Error_LanguageItemsAreMissing">{0} language item(s) are missing in {1}</I></Errors><XSystem.Update><Dialogs><I Name="Info_UpdateAvailable">Version : {0} is available</I><I Name="Info_CheckingForNewVersion">Checking for new version</I></Dialogs></XSystem.Update></Lang>

What I need is binarywrite code to save this to a binary file

Here is a link to my project:

LanguageEditor and DicxFiler download

any help would be great

Thank you



At which senerio race condition occur ?

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

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. 

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


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

Viewing all 31927 articles
Browse latest View live