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

Using C# to export to PDF

$
0
0

Hi guys.  I've got a program that has 2 DataGridView controls on it, as well as 2 images.  This program creates a report that gathers and displays data from the database.  I'm trying to figure out how to export that data, and well, everything that is displayed in the GUI, to a PDF.  I've tried SharpPDF and PDFSharp, but they don't give me the ability to edit things like row height.  I would try ITextSharp, but this is for a company, and we don't want to get a license for third party software unless ABSOLUTELY needed.  I have also tried the DataGridView Extension, but my PDF fails to open because it's corrupt. As well as none of the things listed above seem to be supported by the developers anymore.  

Now, for my question.  Do you guys know of any other third party frameworks or anything that would allow me to export this whole thing into a PDF?  Thank you very much!


please explain this C# code snippet

$
0
0

I found the following code snippet at http://www.sparxeng.com/blog/software/must-use-net-system-io-ports-serialport

byte[] buffer = new byte[blockLimit];
Action kickoffRead = null;
kickoffRead = delegate {
    port.BaseStream.BeginRead(buffer, 0, buffer.Length, delegate (IAsyncResult ar) {
        try {
            int actualLength = port.BaseStream.EndRead(ar);
            byte[] received = new byte[actualLength];
            Buffer.BlockCopy(buffer, 0, received, 0, actualLength);
            raiseAppSerialDataEvent(received);
        }
        catch (IOException exc) {
            handleAppSerialError(exc);
        }
        kickoffRead();
    }, null);
};
kickoffRead();

I mainly program poorly in VB.NET

Would someone explain why:

1.  kickoffRead is declared to be an Action but then set to be a delegate ?

2. the delegate is calling kickoffRead ?

I would like to attempt to convert to VB.NET, but the code is way over my level of understanding.

Any clarification would be appreciated. Thank you.

How to capture Unselected checkbox node in a asp Treeview.

$
0
0

Scenario : Lets say i have a treeView that has 1000 nodes in which User has selected 10 checkboxes and clicked save and refreshes the page. It will trigger a backend logic that will save his checkbox changes to the DB. 

Now User 2 will go to the same treeview and unchecks 5 checkboxes and save it . How do i capture these 5 uncheck boxes treenode in the backend .

For example if the checkbox is checked what we can do is loop through TreeView1.CheckedNodes which captures all the 10 checkboxes that User1 clicked. 

Expectations : Way to figure out how to capture the unchecked checkboxes node which User 2 UnChecked on postback call. i.e 5  

SerialPort vs SerialStream (Device driver experts welcome)

$
0
0

I'm trying to find out if I can dispense completely with the SerialPort class and just use the underlying SerialStream class which exposes async Begin/End directly for reads and writes.

There are a host of problems with SerialPort, for example read this informative article:

http://www.sparxeng.com/blog/software/must-use-net-system-io-ports-serialport

That enginner is 100% correct and when I use SerialPort as he describes I get excellent results, but now I wonder why we even need SerialPort, so has anyone here every use SerialStream directly for serial IO on Windows COM ports?

Thanks

OK - Ignore this question, the SerialStream class is internal ! 

Image Encryption in Visual cryptography

$
0
0
source   code for Sharing a Secret Images with encapsulated Shares in  Visual cryptography for my project 

TcpClient - receives unasked messages, concept

$
0
0
Hello,
I have a client that needs to respond to messages.
The message are XML structure.
It seems to work, the problem where I see it, I read the list and then it will be filled.
 List<string> listMessages = new List<string>();
 
I need your expert knowledge.
Do I have to use a thread-safe list, if so, how?
BlockingCollection<string> bc = new BlockingCollection<string>()
How do I delete the entries?
STEP1
public void Execute()
{
	MyTokenSource = new CancellationTokenSource();
	MyToken = MyTokenSource.Token;
	try
	{
		Task.Run(() =>
		{
			Workingloop(MyToken);  // besser so verwenden
		});//STEP2
public async void Workingloop(CancellationToken token)
{
	int value1 = 0;
	int value2 = 0;
	string value3 = "";
	try
	{
		while (!token.IsCancellationRequested)
		{
			List<string> recList = await SocketClient.ReceiveSocket(SocketDataEchange, token);

			if (recList != null && recList.Count == 1)
			{
				if (recList[0] == "ConnectionReset")
				{
					recList.Clear();
					Stop();
					Connect(IP, Port);
					Execute();
				}
				else
				{
					if (recList[0].Length > 0 && recList[0].Substring(0, 1) != "<")
						recList.Clear();
				}
			}//STEP3
internal class SocketsSendReceive
{
	byte[] Buffer = new byte[1000];
	String ReceiveBuffer = string.Empty;
	int SizeReceive = -1;
	internal async Task<List<string>> ReceiveSocket(Socket sck, CancellationToken myToken)
	{
		return await Task.Run(() =>
		 {
			 List<string> listMessages = new List<string>();
			 while (SizeReceive != 0 && !myToken.IsCancellationRequested)
			 {
				 if (sck.Connected == false)
				 {
					 return null;
				 }

				 try
				 {
				    // Sync
					 SizeReceive = sck.Receive(Buffer, 0, Buffer.Length, SocketFlags.None);
				 }
				 catch (SocketException eS)
				 {
					 Log.Error($"Socket Exception {eS.Message}");

					 listMessages = new List<string>();

					 switch ((SocketError)eS.ErrorCode)
					 {
						 default:
							 listMessages.Add(((SocketError)eS.ErrorCode).ToString());
							 break;
					 }
					 return listMessages;
				 }
				 catch (Exception e1)
				 {
					 break;
				 }

				 ReceiveBuffer += Encoding.ASCII.GetString(Buffer, 0, SizeReceive).Replace('\r', ' ').Replace('\n', ' '); 
				 int lengthFirstTag = ReceiveBuffer.IndexOf(">");
				 if (lengthFirstTag <= 0)
					 continue;
Best regards, Markus

How to write an xml to binarry

$
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







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


How to get year from string have comma separated text ?

$
0
0

problem

How to get year from string have comma separated text ?

i have string have formate as following Branchcode,transactionType,Year,Serial

as example following

string mykey ="1,206,2019,23449";

suppose i need to get value after 2 comma meaning i need to get year 

meaning i need to get 2019

so that how to do that by c sharp please ?

C# System.Timers.Timer. Is there really that much overhead in a winform app vs. console? Example Code

$
0
0

Hi all…

I wanted to create a timer that could app where I could monitor how many times a timer will tick per second. This all came about because I wanted to be able to throttle down how many times I was sending things over a network stream and I wanted to find the sweet spot in milliseconds and using a timer. Think FPS. 

 

To do this I used two System.Timers.Timer objects. 
_tpsTimer (ticks per second)

  • Ticks on a user input interval so I can test to see how often I’d want to trigger based on FPS.
  • Simply increments a counter variable “_tpsCount” tracking how many times its delegate was fired off

_oneSecondTimer

  • Hard coded to 1000 milliseconds, 1 second.
  • Displays the “_tpsCount” variable showing me how many times the _tpsTimer fired its event in one second.

  

I wrote a couple versions of the app. The logic behind these two apps are identical except for the fact that one is a winform one is a console. The two versions I’m most interested in posting about are

  • SystemTimers – A Windows form app using System.Timers.Timer
  • SystemTimersConsole – A console app using System.Timers.Timer

I was surprised at how much of a difference there was in ticks per second between a console app and windows form app.  Is there REALLY that much overhead in a windows form app?  Secondly, am I way off base in using timers for this purpose? Ultimately wanting to create a FPS throttle... How many images I send over a network per second.

The following image shows various tests at different millisecond intervals.  The columns are :

  • Milli Sec column : Millisecond interval.
  • Console : At the given milli sec interval, how many times the timer was triggered for the Console application
  • Win Form :  At the given milli sec interval, how many times the timer was triggered for the Win Form application

Here is the code for the console app.

using System;

namespace SystemTimersConsole
{
    class Program
    {

        // Ticks on 1 second intervals, Used to write _tpsCount every second
        private System.Timers.Timer  _oneSecondTimer;

        // Ticks on user specified interval, used to update _tpsCount variable
        private System.Timers.Timer  _tpsTimer;

        // Represends how many times in 1 second _tpsTimer is fired off. 
        private int _tpsCount;

        // Since timers run in differnt treads than GUI thread, need a delegate to 
        // update the GUI
        public delegate void DisplayTPS( object source, System.Timers.ElapsedEventArgs e );


        static void Main( string[ ] args )
        {
            Program p = new Program();
            p.Reset( );

            // Param specifies millisecond frequency for _tpsTimer
            p.StartTimers( 19 );
            ConsoleKeyInfo i = Console.ReadKey( );
        }



        /// <summary>
        /// _oneSecondTimer tick event. 
        /// Updates the list box with the TPS count information. Function can be called from either 
        /// the GUI thread or one one of timer threads.
        /// </summary>
        /// <param name="state">Not using this state</param>
        private void DisplayData( Object source, System.Timers.ElapsedEventArgs e )
        {
            Console.WriteLine( "TPS COUNT : " + _tpsCount );
            _tpsCount = 0;
        }



        /// <summary>
        /// _tpsTimer tick event handler. Increments the TPS counter indicator.
        /// </summary>
        /// <param name="state"></param>
        private void IncTPSCount( Object source, System.Timers.ElapsedEventArgs e )
        {
            _tpsCount++;
        }

        /// <summary>
        /// Resets all the controls and what not.
        /// </summary>
        private void Reset( )
        {
            if( _oneSecondTimer != null )
                _oneSecondTimer.Dispose( );
            if( _tpsTimer != null )
                _tpsTimer.Dispose( );

            _oneSecondTimer = null;
            _tpsTimer       = null;
            _tpsCount       = 0;
        }


        /// <summary>
        /// Resets controls, timers and restarts timers.
        /// </summary>
        /// <param name="milli">Specifies in milliseconds how frequent to call IncCount</param>
        private void StartTimers( int milli )
        {
            Reset( );
            _oneSecondTimer         = new System.Timers.Timer( 1000 );
            _tpsTimer               = new System.Timers.Timer( milli );

            _oneSecondTimer.Elapsed += DisplayData;
            _tpsTimer.Elapsed       += IncTPSCount;

            _oneSecondTimer.Enabled = true;
            _tpsTimer.Enabled       = true;
        }
    }
}

Here is the code for the Windows Form app
using System;
using System.Windows.Forms;
using System.Threading;


/* ==============================================================================================
 * Shows how to use two the System.Timers.Timer class instances to create a to display how many
 * times a timer will trigger in one second. 
 *  
 * _tpsTimer triggers on a user specified value in the GUI. It will update _tpsCount which
 * holds the number of times _tpsTimer was triggered.
 * 
 * _oneSecondTimer will trigger every 1 second and will display the _tpsTimer value in the
 * list box showing how many times _tpsTimer was triggered in 1 second.
 * 
 * These methods can be used to try and control how fast something happens within 1 second.  This
 * is not SCIENTIFICALLY accurate, but it might be good enough to throttle down something like 
 * Frames Per Second to prevent flooding the network with too much streaming media. 
 * 
 * Because the timers run in a separate thread, the DisplayData function must use multithreading
 * techniques to allow cross threaded data to be used in the GUI.
 ============================================================================================= */


namespace FPSTimer
{
    public partial class FormSystemTimers : Form
    {
        // Ticks on 1 second intervals, used to trigger list box updates
        private System.Timers.Timer  _oneSecondTimer;

        // Ticks on user specified interval, used to update _tpsCount variable
        private System.Timers.Timer  _tpsTimer;

        // Represends how many times in 1 second _tpsTimer is fired off. 
        private int _tpsCount;

        // Since timers run in differnt treads than GUI thread, need a delegate to 
        // update the GUI
        public delegate void DisplayTPS( object source, System.Timers.ElapsedEventArgs e );


        public FormSystemTimers( )
        {
            InitializeComponent( );

            // Set initial state
            Reset( );
        }

        /// <summary>
        /// _oneSecondTimer tick event. 
        /// Updates the list box with the TPS count information. Function can be called from either 
        /// the GUI thread or one one of timer threads.
        /// </summary>
        /// <param name="state">Not using this state</param>
        private void DisplayData( Object source, System.Timers.ElapsedEventArgs e )
        {

            if( this.lb1.InvokeRequired )
            {
                // Create the delegate and specify which function to call.
                DisplayTPS d = new DisplayTPS( DisplayData );
                this.Invoke( d, new object[ ] { source, e } );
            }
            else
                lb1.Items.Add( "TPS COUNT : " + _tpsCount );

            _tpsCount = 0;
        }



        /// <summary>
        /// _tpsTimer tick event handler. Increments the TPS counter indicator.
        /// </summary>
        /// <param name="state"></param>
        private void IncTPSCount( Object source, System.Timers.ElapsedEventArgs e )
        {
            _tpsCount++;
            Console.WriteLine( _tpsCount );
        }


        /// <summary>
        /// Resets all the controls and what not.
        /// </summary>
        private void Reset( )
        {
            if( _oneSecondTimer != null )
                _oneSecondTimer.Dispose( );
            if( _tpsTimer != null )
                _tpsTimer.Dispose( );

            _oneSecondTimer = null;
            _tpsTimer       = null;

            lb1.Items.Clear( );
            _tpsCount = 0;

            if( tbMilli.Text == "" )
                tbMilli.Text = "30";
        }


        /// <summary>
        /// Resets controls, timers and restarts timers.
        /// </summary>
        /// <param name="milli">Specifies in milliseconds how frequent to call IncCount</param>
        private void StartTimers( int milli )
        {
            Reset( );
            _oneSecondTimer = new System.Timers.Timer( 1000 );
            _tpsTimer       = new System.Timers.Timer( milli );

            _oneSecondTimer.Elapsed += DisplayData;
            _tpsTimer.Elapsed       += IncTPSCount;

            _oneSecondTimer.Enabled = true;
            _tpsTimer.Enabled = true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click( object sender, EventArgs e )
        {
            if( tbMilli.Text == "" )
                return;

            int milli = Int32.Parse( tbMilli.Text );

            if( milli > 0 && milli < 1001 )
                StartTimers( milli );
        }


        /// <summary>
        /// Calling this to kill the timers. If you don't do this, they continue to run after the
        /// form starts to shut down which causes an exception. This is because the timer will still
        /// try to call their tick handlers (updating the list), but the form controls have been killed, 
        /// so an exception happens.  So, kill everyting BEFORE allowing the form to close.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosing( object sender, FormClosingEventArgs e )
        {
            Reset( );
        }
    }
}

Any feedback is greatly appreciated!

Thanks
Rick


Rick



AesCng Class

$
0
0

Hello... I upgraded to the .NET Framework 4.6.2 so I could take advantage of the new AesCng Class in the Cryptography namespace.

However, when comparing it "side by side" with regular Aes there seems to be no difference. For example this function...

private string AesCrypto()
{
    string DataToEncrypt = "Hello!";
    byte[] Key = new byte[32] { };
    byte[] IV = new byte[16] { };

    using (AesCryptoServiceProvider AES = new AesCryptoServiceProvider())
    {
        byte[] DataByteArray = Encoding.UTF8.GetBytes(DataToEncrypt);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, AES.CreateEncryptor(Key, IV), CryptoStreamMode.Write);
        cs.Write(DataByteArray, 0, DataByteArray.Length);
        cs.FlushFinalBlock();

        return Convert.ToBase64String(ms.ToArray());
    }
}

returns the value: ylsH2mi5zN3DOxdvL00fzQ==

And so does this function:

private string AesCrypto()
{
    string DataToEncrypt = "Hello!";
    byte[] Key = new byte[32] { };
    byte[] IV = new byte[16] { };

    using (AesCng AES = new AesCng())
    {
        byte[] DataByteArray = Encoding.UTF8.GetBytes(DataToEncrypt);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, AES.CreateEncryptor(Key, IV), CryptoStreamMode.Write);
        cs.Write(DataByteArray, 0, DataByteArray.Length);
        cs.FlushFinalBlock();

        return Convert.ToBase64String(ms.ToArray());
    }
}

They both return the same result: ylsH2mi5zN3DOxdvL00fzQ==

The only difference is one uses AesCryptoServiceProvider and the other uses AesCng.

Should the results be the same? Or should AesCng be different? Perhaps I am not implementing it correctly?

I could not find any clear examples on microsoft.com or any other site, explaining the use of AesCng.

Any help would be greatly appreciated. Thank you!

How do I make a program that receives commands from an Android phone

$
0
0

Title says it all I have never ever done this before but it would be fun I want to make a Android app that when I press a button on the Android app it sends a signal to my PC with a program that is listening and when it receives the button click the PC would display a message box just for an example

How can I achieve that?

Calling 3rd Part Code asynchronously

$
0
0

I am customizing some 3rd party code. I want to call some code asynchronously which is currently not working in async/await.

Ex :- Casting an object  - [(Root)system] boot Root and system are 3rd party code.

Note:- This works if i run it synchronously.

inside an async/await which throws exception, Function requires all threads to run and then null reference Exception.

Does this means it involves UI somehow?? As i believe code involving UI cannot run asynchronously.

If it is not UI related then how to rectify this?

linq expression for string comparison that counts equal words

$
0
0

Hello there,


I want to define a linq expression that finds all list items they matches my needle best. For example I have the following list and needle: 


List<string> colors = new List<string>();
colors.Add("yello dark blue orange");
colors.Add("red apple green");
string needle = "blue orange apple"

Now I want to get all list items back where the needle fits best. That means  "blue orange apple" and "yellow dark blue orange" have 2 words in common and  "blue orange apple" and "red apple green" only one, so it should return a list that contains the element "yellow dark blue orange".


How to achieve long polling to url using .net 3.5 framework

$
0
0

Hi sir,

Please hep me to make log polling to particular URL.

Eg: Url = http://<ip>/testsample/main.php

for the above url i have to make a http request. This url response returns the interval value.

Based on the interval again has to make a http request to same url. It keeps making the request.

Please help me with snippet of code to do this.

thanks in advance,

Ravi




Data Access Object Pattern C#

$
0
0
    public class Person
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }




    public interface IPerson
    {
        int Insert(Person person);
        int update(Person person);
        int delete(int personId);
    }



    //Data Access Layer
    public class PersonRepository:IPerson
    {
        public int Insert(Person person)
        {
            //sql code here
        }

        public int update(Person person)
        {
            //sql code here
        }

        public int delete(int personId)
        {
            //sql code here
        }
    }


    //Business Layer
    public class PersonBLL:IPerson
    {
        PersonRepository personRepository=new PersonRepository();
        public int Insert(Person person)
        {
            return personRepository.Insert(person);
        }

        public int update(Person person)
        {
            return personRepository.update(person);
        }

        public int delete(int personId)
        {
            return personRepository.delete(personId);
        }
    }

This code was derived from the Data Access Object Pattern, i just added a business layer that acts as a wrapper so that the UI layer don't need to call the data layer directly. Now, i'm pretty confuse if i'm using or do i need the interface at all because all it does it to make sure that all the methods will be implemented.

Data Object Pattern Example

By the way im using Dapper to map my sql results to objects. 

Regards

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

how to reduce number of trips to database

$
0
0

Each Item in our products database table has its own General Ledger (GL) sales account code and corresponding description and Inventory Account and Inventory desription. Now only the account code are stored in the products table - which means when I have the GL Sales Account from the products table I have to run a query in the charts of accounts table to get proper description for it. and then in addition Inventory account code meaning I have to do another query for the Inventory account description from the same table. these are just two fields only. products also have a Cost of Goods Sold Account and Inventory Adjustment Account meaning I have to do so many round trips to the database to retrieve the description of these codes. My question is How can I reduce the Number of round trips to the database?

TxtSaleGLCode.Text= Convert.ToString(row["GLSalesAccount"]);
                TxtSalesGLDescription.Text = ProceduresClass.GetGLDescriptionFromChartMaster(Convert.ToString(row["GLSalesAccount"]));
                TxtInventoryAccountGLCode.Text=Convert.ToString(row["GLInventoryAccount"]);
                TxtInventoryAccountGLDescription.Text = ProceduresClass.GetGLDescriptionFromChartMaster(Convert.ToString(row["GLInventoryAccount"]));


If you think it you can achieve it

how to publish an application

$
0
0
using community c#.  all I need to know is how to publish my windows PC app to a folder on a customers PC, so that the .exe file can be seen in that folder.  At the present time,  I use the publish wizard to copy the instal files to a USB stick using the publish to CD ROM method.  However,  when installing on another machine,  the installer setup.exe does not ask for a destination location, it just "installs" it somewhere hidden in the operating system.  the app runs when i click the shortcut, but the shortcut properties do not reveal where the app has been placed,  its just hidden somewhere.  Conventional installers always ask for a destination directory, but Visual Studio seems to lack this feature.

Changing individual markers in a c# chart

$
0
0
I have a c# chart (System.Windows.Forms.DataVisualization.Charting) that I plot a few points with markers.  I add a new Series to the Chart, set the ChartType toSeriesChartType.FastPoint, and set the MarkerStyle to

MarkerStyle.Circle.  I want to change the marker style for one point to MarkerStyle.Diamond, say the 3rd point, which I do aschrtPlot.Series[name].Points[2].MarkerStyle = MarkerStyle.Diamond;  However, when I display the chart, all the points have the Circle marker style, which is the style I set when adding the series.  I checked in the debugger that the marker style for the 3rd point is Diamond but it's not displaying as a diamond.  Is there something else I need to set to get a different marker style for one point of the series?

Viewing all 31927 articles
Browse latest View live


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