PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label console-application. Show all posts
Showing posts with label console-application. Show all posts

Monday, November 7, 2022

[FIXED] When I finish my task of converting exchange rate , I want to return to the main menu that appears when I start the program

 November 07, 2022     c#, console-application, csharpcodeprovider, menu     No comments   

Issue

I want to return to the main menu not restarting the program all over again to change the type of conversion .. Any help please ? I will be thankful if somebody here helped me ..

using System;

namespace Assignment_1_Csharp
{
    internal class Program
    {
        static void Main(string[] args)
        {      int choice;
            double val,EGP;
            Console.WriteLine("Enter your Choice :\n 1- Dollar to EGP \n 2- EGP to Dollar  ");
            choice = int.Parse(Console.ReadLine());

            switch (choice)
            {
                case 1:
                    double dollar;
                    Console.Write("Enter the Dollar Amount :");
                    dollar = double.Parse(Console.ReadLine());
                    Console.Write("Enter the Dollar Exchange Rate :");
                    val = double.Parse(Console.ReadLine());
                    EGP = dollar * val;
                    Console.WriteLine("{0} Dollar Equals {1} EGP", dollar, EGP);
                    break;
                case 2:
                    Console.Write("Enter the EGP Amount :");
                    EGP = double.Parse(Console.ReadLine());
                    Console.Write("Enter the Dollar Exchange Rate :");
                    val = double.Parse(Console.ReadLine());
                    dollar = EGP / val;
                    Console.WriteLine("{0} EGP Equals {1} Dollars", EGP, dollar);
                    break;
               
            }
            Console.ReadLine();
        }
    }
}

Solution

One way to solve this is using a do-while loop. The following code will run through the choice selection and conversion and then ask user to continue. If the selection is "y" then it will ask the user to choose again otherwise exit the main method.

public static void Main(string[] args)
{
    int choice;
    double val, EGP;
    string userSelection = "y";
    do
    {
        Console.WriteLine("Enter your Choice :\n 1- Dollar to EGP \n 2- EGP to Dollar  ");
        choice = int.Parse(Console.ReadLine());

        switch (choice)
        {
            case 1:
                double dollar;
                Console.Write("Enter the Dollar Amount :");
                dollar = double.Parse(Console.ReadLine());
                Console.Write("Enter the Dollar Exchange Rate :");
                val = double.Parse(Console.ReadLine());
                EGP = dollar * val;
                Console.WriteLine("{0} Dollar Equals {1} EGP", dollar, EGP);
                break;
            case 2:
                Console.Write("Enter the EGP Amount :");
                EGP = double.Parse(Console.ReadLine());
                Console.Write("Enter the Dollar Exchange Rate :");
                val = double.Parse(Console.ReadLine());
                dollar = EGP / val;
                Console.WriteLine("{0} EGP Equals {1} Dollars", EGP, dollar);
                break;

        }
        Console.WriteLine("Enter Y to choose again...");
        userSelection = Console.ReadLine();
    }
    while (userSelection.ToLower() == "y");
}

You can change the text messages and selection to anything you want.



Answered By - Barkha Jain
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, September 6, 2022

[FIXED] How to async task and Mailchimp API v3.0

 September 06, 2022     automation, c#, console-application, mailchimp-api-v3.0     No comments   

Issue

I am trying to get from MailChimp a MailChimp List Collection. I have set up the process as displayed in the example on MailChimp.net for getting all lists but it exits out before the list is returned unless I use a Console read after the task is called. How do I get this supposedly simple task to work?

static void Main(string[] args)

{

    AddUpdateMailChimp();

    Console.Read();

}

static async void AddUpdateMailChimp()

{

    lstIDs = await Get_MailChimp_Info();

    for(int i = 0; i < lstIDs.Count; i++)

    {

        AddUpDateMailChimpAsync(lstIDs[i]);
    }

}

private static async Task< List< string >> Get_MailChimp_Info()

{

    var lstIDs  = new List< string > ();

    apikey = GetApiKey() //from config file

    manager = new MailChimpManager(apikey);
    //............below line is where it bombs unless I use a concole.Read in the main..........//

   **IEnumerable< MailChimp.Net.Models.List> mailChimpListCollection = await manager.Lists.GetAllAsyunc().ConfigureAwait( continueOnCapturedContext: false);**

    ............catch statements

    //.......foreach loop to get the list Ids
}

Solution

I had this problem recently. Because AddUpdateMailChimp() is async, then the Main() method is continuing execution as soon as it hits it, and not waiting on the result.

Also the method returns void so it's seen as fire-and-forget.

If you want to be able to await it, then it should return a task.

That way, in Main() you can do

var result = AddUpdateMailChimp().Result;



Answered By - Barry O'Kane
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, August 16, 2022

[FIXED] How to print numbers horizontally in line in Console?

 August 16, 2022     c#, console-application, output     No comments   

Issue

While I am using this code (below) with Visual Studio 2012, the answers are in vertical order.

How can I get answers in horizontal order using VS 2012

Below is my code that I getting output in vertical order: how may I achieve the same result in a horizontal manner?

Are there any settings in Visual Studio for getting output in horizontal or vertical?

class RandomNumbers
{
    private static Random random = new Random();
    static void Main(string[] args)
    {
        var numbers = GenerateRandomNumbers(200,100,10);
        foreach (var temp in numbers)
        {
            Console.WriteLine(temp+" ");
        }
    }
    static IEnumerable<int> GenerateRandomNumbers(int NumberOfElements)
    {
        return Enumerable.Range(0,NumberOfElements-1).OrderBy(n=>random.Next());
    }
    static IEnumerable<int> GenerateRandomNumbers(int min, int max, int numberOfElement)
    {
        return Enumerable.Range(0, numberOfElement - 1).Select(n => random.Next(max, min));
    }
}

Solution

Try using Write() instread of WriteLine()

class RandomNumbers
{
    private static Random random = new Random();
    static void Main(string[] args)
    {
        var numbers = GenerateRandomNumbers(200,100,10);
        foreach (var temp in numbers)
        {
            Console.Write(temp+" ");
        }
    }
    static IEnumerable<int> GenerateRandomNumbers(int NumberOfElements)
    {
        return Enumerable.Range(0,NumberOfElements-1).OrderBy(n=>random.Next());
    }
    static IEnumerable<int> GenerateRandomNumbers(int min, int max, int numberOfElement)
    {
        return Enumerable.Range(0, numberOfElement - 1).Select(n => random.Next(max, min));
    }
}


Answered By - Richard Barker
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, August 11, 2022

[FIXED] How do I make my writeline output display the numeric value to the nearest 2 decimal?

 August 11, 2022     c#, console-application, decimal, rounding     No comments   

Issue

I am just needing to finish up this program for my assignment and I have completed the task that I want it to perform, yet I cannot for the life of me figure out how to make my output display the number value to the second decimal. (For example: 35.50)

My program is meant to take the average of values, and give the numeric average in decimals. It does do that, but the decimal string is way longer than 2 decimal places. I'm hoping to get some advice on how to clean this up, and please give all answers with the explanation. Thank you so much! (The program I am using is visual studios 2017, and I am creating this code within the console app of C#)

static void Main(string[] args)
    {

        decimal counter = 1;
        decimal sum = 0;
        decimal totalLoops = 3;


        while (counter <= totalLoops)
        {
            Console.WriteLine("Please enter test score here:");
            string scoreInput = Console.ReadLine();
            decimal score;
            decimal.TryParse(scoreInput, out score);
            sum += score;
            counter++;

        }

        Console.WriteLine("Your average is {0}", decimal.Round(sum, 2) / decimal.Round(totalLoops, 2));
        Console.ReadKey();

    }

}

Solution

You can use Math.Round

Console.WriteLine("Your average is {0}", Math.Round(decimal.Round(sum, 2) / decimal.Round(totalLoops, 2), 2, MidpointRounding.AwayFromZero));


Answered By - Kei
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, July 25, 2022

[FIXED] How to get an array from appsettings.json file in .Net 6?

 July 25, 2022     .net-6.0, arrays, console-application, json     No comments   

Issue

I've read this excellent SO post on how to get access to the appsettings.json file in a .Net 6 console app.

However, in my json file I have several arrays:

"logFilePaths": [
    "\\\\server1\\c$\\folderA\\Logs\\file1.log",
    "\\\\server2\\c$\\folderZ\\Logs\\file1A1.log",
    "\\\\server3\\c$\\folderY\\Logs\\file122.log",
    "\\\\server4\\c$\\folderABC\\Logs\\fileAB67.log"
  ],

And I get the results if I do something like this:

    var builder = new ConfigurationBuilder().AddJsonFile($"appsettings.json", true, true);
    var config = builder.Build();

    string logFile1 = config["logFilePaths:0"];
    string logFile2 = config["logFilePaths:1"];
    string logFile3 = config["logFilePaths:2"];

But I don't want to have to code what is effectively an array into separate lines of code, as shown.

I want to do this:

string[] logFiles = config["logFilePaths"].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

But it gives me an error on config["logFilePaths"] saying it's null.

Why would that be null?


Solution

To access the logFilePaths as an array, you want to use the Get<T> extension method:

string[] logFilePaths = config.GetSection("logFilePaths").Get<string[]>();


Answered By - 0xced
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 10, 2022

[FIXED] How to assign objects from two different classes?

 July 10, 2022     c#, class, console-application, reference     No comments   

Issue

I have two constructors Employee Employee(string id, string FirstName, string LastName) and ProjectProject(string PID, string PName) . To add an employee or view the whole project list, I have created a business logic :

   public class Employeeclass
    {
        public List<Employee> Employees { get; set; } = new List<Employee>();

        public void AddEmployee(Employee employee)
        {
            Employees.Add(employee);
        }

        public List<Employee> GetAllEmployee()
        {
            return Employees;
        }
}     
public class Projectclass
    {
        public List<Project> Projects { get; set; } = new List<Project>();

        public void AddProject(Project project)
        {
            Projects.Add(project);
        }

        public List<Project> GetAllProject()
        {
            return Projects;
        }
    }

In this business logic, I want to assign a project to an employee. For this I generated a separate constructor Assign(string EmpId, string PID)and created a class to assign the projects. First I add a employee and then a project. By using EmpId and PID, I want to assign the projects to employee. It was possible to do so when all the business logic was under a single class.

public class Assignclass
    {
        public List<Assign> Assigns { get; set; } = new List<Assign>();
        //assign employees to project
        public void Add(Assign assign)
        {
            var id = assign.EmpId;
            var pid = assign.PID;
            var emp = Employees.Find(a => a.EmpId == id);
            var prjct = Projects.Find(c => c.PID == pid);
            if (emp != null || prjct != null)
            {
                Assigns.Add(assign);
            }
        }
}

I could use this code when I have put Employeeclass, Projectclass and Assignclass as a single class. Now that I have segregated the classes in Employeeclass, Projectclass, Assignclass; I can't use the same code as Employees and Projects can't exist without context so I created reference variables for Employees and Projects.

public void Add(Assign assign)
        {
            Employeeclass classA = new Employeeclass();
            Projectclass classB = new Projectclass();
            
            List<Employee> Employes = classA.Employees;
            List<Project> Projcts = classB.Projects;
            //List<Assign> Assignss = classC.Assigns;
            var id = assign.EmpId;
            var pid = assign.PID;
            var emp = Employes.Find(a => a.EmpId == id);
            var prjct = Projcts.Find(c => c.PID == pid);
            if (emp != null || prjct != null)
            {
                Assigns.Add(assign);
            }
        }

But it shows while debugging that there are no elements in Employes. I can't use Find to find an employee with the same EmpId; same with Projects and Projcts. How should I assign the project to employees and what am I doing wrong?


Solution

In your public void Add(Assign assign) function you make classA and classB, these are new objects of this class and have no values in them. If you want to use the function like this you could make the function like this: public void Add(Assign assing, Employeeclass classA, Projectclass classB) ... And then you can give your existing object with there value with them.



Answered By - Jorne Schuurmans
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, February 15, 2022

[FIXED] $_SERVER['SERVER_NAME'] is not working with console application in Yii framework

 February 15, 2022     console-application, php, yii     No comments   

Issue

When i am trying to run my photoResizer command like this /var/www/myProject/proted/yiic photoResizer

i am getting this error.

PHP Error[8]: Undefined index: SERVER_NAME
in file /var/www/myProject/protected/components/UploadHandler.php at line 190
#0 /var/www/myProject/protected/components/UploadHandler.php(45):  
UploadHandler->get_full_url()
#1 /var/www/myProject/protected/commands/PhotoResizerCommand.php(37):   
UploadHandler->__construct()
#2 /var/www/myProject/framework/console/CConsoleCommandRunner.php(71):    
PhotoResizerCommand->run()
#3 /var/www/myProject/framework/console/CConsoleApplication.php(92): 
CConsoleCommandRunner->run()
#4 /var/www/myProject/framework/base/CApplication.php(180): 
CConsoleApplication->processRequest()
#5 /var/www/myProject/framework/yiic.php(33): CConsoleApplication->run()
#6 /var/www/myProject/protected/yiic.php(7): require_once()
#7 /var/www/myProject/protected/yiic(4): require_once()

I need to solve this problem or any alternative to run a php script via command line in yii framework.

Thanks.


Solution

Quite obviously there's no "server" when running an app from the command line, so you cannot use that variable for anything. Apparently UploadHandler is hard coded to expect to be executed in the context of a web request to handle files uploaded within the request (which, you know, makes sense). Since you're not in a web request context, it fails.



Answered By - deceze
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, January 12, 2022

[FIXED] Yii2 - Getting unknown property: yii\console\Application::user

 January 12, 2022     console-application, php, yii, yii2, yii2-advanced-app     No comments   

Issue

I am trying to run a console controller from the terminal, but i am getting this errors every time

Error: Getting unknown property: yii\console\Application::user

here is the controller

class TestController extends \yii\console\Controller {

public function actionIndex() {
    echo 'this is console action';
} }

and this is the concole config

return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'modules' => [],
'components' => [
    'log' => [
        'targets' => [
            [
                'class' => 'yii\log\FileTarget',
                'levels' => ['error', 'warning'],
            ],
        ],
    ],
],
'params' => $params];

I tried running it using these commands with no luck

php yii test/index
php yii test
php ./yii test

can anyone help please?


Solution

Console application does not have Yii->$app->user. So, you need to configure user component in config\console.php.

like as,

config\console.php

 'components' => [
 .........
 ......
        'user' => [
            'class' => 'yii\web\User',
            'identityClass' => 'app\models\User',
            //'enableAutoLogin' => true,
        ],
        'session' => [ // for use session in console application
            'class' => 'yii\web\Session'
        ],
 .......
]

More info about your problem see this : Link

OR

Visit following link : Yii2 isGuest giving exception in console application

Note : There's no session in console application.



Answered By - GAMITG
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, January 9, 2022

[FIXED] Yii 1 Console Application Environment Variables

 January 09, 2022     console-application, environment-variables, php, yii     No comments   

Issue

For a Yii 1 web application, I am using the symfony/dotenv library to read and load environment variables from a .env file. To do this, I added a code in the index.php file,

require 'vendor/autoload.php'; //autoload for composer

if(file_exists('/path/to/.env')){
    $dotenv = new Symfony\Component\Dotenv\Dotenv();
    $dotenv->load(__DIR__.'/path/to/.env');
}
else{
   // Missing .env file
   exit;
}

This works well with the web application. However, for Yii console applications, this does not work because index.php is not being loaded. Can this be done inside the console.php file? How?


Solution

For console application you can do the same in protected/yiic.php. This file is used for bootstrap when you call ./yiic, in similar way as index.php is loaded on web request.



Answered By - rob006
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing