Using static method from other file without class name [duplicate] - c#

This question already has answers here:
static imports in c#
(5 answers)
Closed 1 year ago.
I tried to use something like using Printer; but it doesn't work.
I just want use P(); instead of Printer.P();
File Printer.cs
using System;
namespace animals
{
public class Printer
{
public static void P()
{
P("\a");
}
public static void P(object val, bool doEnterAfterLine = true, bool printInOneLine = false)
{
P(val.ToString());
if (doEnterAfterLine)
Console.WriteLine(); //enter
}
static void P(bool printSeparator = false)
{
if (printSeparator == false)
return;
P("---------------------------------------------------------", true);
}
static void P(string value = "none", bool modifyColor = false, bool ding = false, bool printInOneLine = false)
{
var oldColor = Console.ForegroundColor;
if (modifyColor)
Console.ForegroundColor = ConsoleColor.Magenta;
if (printInOneLine)
Console.Write(value + " ");
else
Console.WriteLine(value);
Console.ForegroundColor = oldColor; //recover color
if (ding)
{
Console.Write("\a");
}
}
}
}
File Program.cs
using System;
// this resolve problem: using static animals.Printer;
namespace animals
{
class Program
{
static void Main(string[] args)
{
Printer.P(); // it works
P(); // info: does not exist in current context
}
}
}

Use using static <namespace>.<class>; to access the members of <class> without qualifying its name.
using static animals.Printer;

Related

Add color to Console.ReadLine();

I'm using https://github.com/tomakita/Colorful.Console, but I don't mind solutions that wouldn't include this nuget.
using System;
using System.Collections.Generic;
using System.Drawing;
using Colorful;
namespace CMDAdv
{
class Program
{
static void Main()
{
Colorful.Console.WriteLineFormatted(Dialog.intro, Color.Tomato, ColorfulDescription());
Advance("What will you do?", "examine shimmer");
Colorful.Console.Clear();
Advance("continue", "no");
}
static void Advance(string writeOutput, string required)
{
string input;
Colorful.Console.WriteLine(writeOutput, Color.BlanchedAlmond);
input = ReadLine();
while (!input.Equals(required, StringComparison.OrdinalIgnoreCase))
{
Colorful.Console.WriteLine("Try again.", Color.Red);
input = Colorful.Console.ReadLine();
}
}
static string ReadLine(string input, string color)
{
input = Colorful.Console.ReadLine();
color = Colorful.Console.ToString(Color.Red);
return input;
}
static Formatter[] ColorfulDescription()
{
Formatter[] coloredText = new Formatter[]
{
new Formatter("shimmer", Color.LightBlue)
};
return coloredText;
}
}
}
As you can see I tried to add color to ReadLine using a method but that doesn't really work. Anyone know how to do this?
I'm using Colorful.Console, also I have tried different ways such as ReadLine(Color.Pink); etc etc.

How to fix looping issue, even though no loop implemented?

Ok, so I am trying to figure out why I am having a looping issue. The intention of the method GetNewDvdInfo() is to return a new dvd class with 5 properties and will be passed on to DvdController.cs in the CreateDvd() method and will then display all the dvds and the dvd the user added. The problem is that the GetNewDvdInfo() method is repeating itself, but when I was returning null instead, it was not looping.
DvdView.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DvdManager.Models;
/*
GetMenuChoice() : int
GetNewDvdInfo(): Dvd
DisplayDvd(Dvd dvd) : void
EditDvdInfo(Dvd dvd) : Dvd
SearchDvd() : int
ConfirmRemoveDvd(Dvd) : boolean
*/
namespace DvdManager.View
{
public class DvdView
{
public int GetMenuChoice()
{
string input;
int choice;
Console.Clear();
Console.WriteLine("Press 1 to display movies");
Console.WriteLine("Press 2 to add movie");
input = Console.ReadLine();
if (int.TryParse(input, out choice))
{
switch (choice)
{
case 1:
break;
case 2:
break;
default:
Console.WriteLine("Invalid input");
break;
}
}
return choice;
}
public Dvd GetNewDvdInfo() //looping here
{
string inputReleaseYear;
string inputRating;
int id = 4;
string readTitle;
int readReleaseYear;
string readDirector;
float readRating;
Console.WriteLine("What is the Title of the DVD?");
readTitle = Console.ReadLine();
Console.WriteLine("What is the Release Year of the DVD?");
inputReleaseYear = Console.ReadLine();
int.TryParse(inputReleaseYear, out readReleaseYear);
Console.WriteLine("Who is the Director of the DVD?");
readDirector = Console.ReadLine();
Console.WriteLine("What is the star rating of the DVD?");
inputRating = Console.ReadLine();
float.TryParse(inputRating, out readRating);
var dvd = new Dvd(id, readTitle, readReleaseYear, readDirector, readRating);
Dvd newDvd = GetNewDvdInfo();
return dvd;
}
public void DisplayDvd(Dvd dvd)
{
}
public Dvd EditDvdInfo(Dvd dvd)
{
return null;
}
public int SearchDvd()
{
return 0;
}
public Boolean ConfirmRemoveDvd(Dvd dvd)
{
return false;
}
}
}
DvdController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DvdManager.Models;
using DvdManager.Data;
using DvdManager.View;
/*
Run() : void
Private CreateDvd(): void
Private DisplayDvds(): void
Private SearchDvds(): void
Private EditDvd() : void
Private RemoveDvd() : void
*/
namespace DvdManager.Controllers
{
public class DvdController
{
public DVDList _dvds = new DVDList();
public void Run()
{
Console.WriteLine("Welcome To Dvd Manager");
DvdView view = new DvdView();
var pass = view.GetMenuChoice();
if (pass == 1)
{
CreateDvd();
}
else if (pass == 2)
{
view.GetNewDvdInfo();
CreateDvd();
}
else
Console.WriteLine("Invalid.");
}
private void CreateDvd() //Create
{
var myView = new DvdView();
var dvdInfos = myView.GetNewDvdInfo();
List<Dvd> Dvds = _dvds.GetList();
Dvds.Add(new Dvd(0, "Batman", 2010, "Bruce", 4));
Dvds.Add(new Dvd(1, "Superman", 2009, "John", 4));
Dvds.Add(new Dvd(2, "Wonderwoman", 2012, "Omar", 4));
Dvds.Add(dvdInfos);
DisplayDvds();
}
private void DisplayDvds() //Read List<Dvd> dvds
{
List<Dvd> Dvds = _dvds.GetList();
for (int i = 0; i < Dvds.Count; i++)
{
Console.WriteLine(Dvds[i]);
}
RemoveDvd();
}
private void SearchDvds() //List
{
}
private void EditDvd(int id, Dvd dvd) //Update
{
}
private void RemoveDvd() //Delete int id
{
List<Dvd> Dvds = _dvds.GetList();
//Dvds.RemoveAt(Dvds[1]);
Dvds.Remove(Dvds.Single(x => x.Id == 1));
Console.WriteLine("Removed movie from list:");
for (int i = 0; i < Dvds.Count; i++)
{
Console.WriteLine(Dvds[i]);
}
}
}
}
You are making a recursive call at the end of GetNewDvdInfo(), just remove it.
You are calling this method recursively here:
var dvd = new Dvd(id, readTitle, readReleaseYear, readDirector, readRating);
Dvd newDvd = GetNewDvdInfo(); //!!!
return dvd;
Hence the looping. It seems like this line of code is not needed.

Invoking A Method From Another File C#

I'm having trouble calling my methods. I have 2 separate files. When the user types S then the shake method in my other file will be invoked. So then when the user gets the answer it will be random.
I confused about how to bring that method in another file. Below are both files.
Program.cs:
static void Main(string[] args)
{
Console.WriteLine("Main program!");
Console.WriteLine("Welcome to the Magic 8 Ball");
Console.WriteLine("What would you like to do?");
Console.WriteLine("(S)hake the Ball");
Console.WriteLine("(A)sk a Question");
Console.WriteLine("(G)et the Answer");
Console.WriteLine("(E)xit the Game");
Magic8Ball_Logic.Magic8Ball ball = new Magic8Ball_Logic.Magic8Ball();
string input = Console.ReadLine().ToUpper();
public static string userAnswer = "";
do
{
if (input == "S")
{
if (userAnswer != null)
{
Console.WriteLine("Searching the Mystic Realms(RAM) for the answer");
}
else
{
//Call Method Shake()
}
}
else if (input == "A") {
userAnswer = Console.ReadLine();
}
else if (input == "G") {
//Call Method GetAnswer()
}
} while (input != "E");
}
Magic8Ball.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Magic8Ball_Logic
{
public class Magic8Ball
{
private List<string> _answers;
private int _currentIndex;
private string randomString;
public Magic8Ball()
{
_answers = new List<string>();
_answers.Add("It is certain.");
_answers.Add("It is decidedly so.");
_answers.Add("Without a doubt.");
}
public Magic8Ball(List<string> answers)
{
//I won't use the 20 default. use the ones passed in .
_answers = answers;
}
public void Shake()
{
//picking the index of the answer to show the user
Random r = new Random();
int index = r.Next(_answers.Count);
randomString = _answers[index];
}
public string GetAnswer()
{
//using the index picked by shake to return the answer
//return "";
return randomString;
}
public int AnswerCount
{
get { return _answers.Count; }
}
/* public override string ToString()
{
foreach (var el in _answers)
{
return el;
}
}*/
}
}
First of all you must create an object of this class,then invoke the method.
**Edit**
ball.Shake();
As it was written here: https://stackoverflow.com/a/55986849/10128127
Your Program.cs should be updated like:
replace this comment
//Call Method Shake() with
ball.Shake();
replace this comment
//Call Method GetAnswer() with
ball.GetAnswer();

How can I get excel to update spreadsheet for Excel-DNA RTD?

I am using excel-DNA example as basis for this test.
I want excel to show my updated data in cell B1 every 1 second.
This works fine for about the first 5 secs, then I get a timer and the have to wait for function finish to see only the last value.
How do I force the update to be shown on the spreadsheet at each cycle of the loop?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExcelDna.Integration;
using System.Threading.Tasks;
using System.Diagnostics;
namespace BTPRTD
{
class Program
{
static void Main(string[] args)
{
}
}
public static class MyFunctions
{
public static MouseData MData;
[ExcelFunction(Description = "My first .NET function")]
public static string SayHello(string name)
{
//Debugger.Launch();
MData = new MouseData ();
Task.Factory.StartNew(() =>
{
ExcelAsyncUtil.QueueAsMacro(() =>
{
KeepWritingData();
});
});
return "Hello " + name;
}
public static void KeepWritingData()
{
var refB1 = new ExcelReference(0, 0, 1, 1, "Sheet1");
string dataTxt = "";
for (int i = 0; i < 100; i++)
{
try
{
MouseData .CurrentPriceData CPD = MData.GetCurrentPriceNT("White mouse");
dataTxt = CPD.AsString();
}
catch (Exception)
{
dataTxt = "Data Unavailable";
}
refB1.SetValue("Ding: " + i + " " + dataTxt);
System.Threading.Thread.Sleep(1000);
}
}
}
}
Excel supports a type of worksheet function called RealTimeData (RTD), which is what you should use for your scenario.
Follow the examples in the "Samples" GitHub repository. In special, take a look at the RtdClocks example that uses an Observable Timer:
public static class RtdClock
{
[ExcelFunction(Description = "Provides a ticking clock")]
public static object dnaRtdClock_Rx()
{
string functionName = "dnaRtdClock_Rx";
object paramInfo = null; // could be one parameter passed in directly, or an object array of all the parameters: new object[] {param1, param2}
return ObservableRtdUtil.Observe(functionName, paramInfo, () => GetObservableClock() );
}
static IObservable<string> GetObservableClock()
{
return Observable.Timer(dueTime: TimeSpan.Zero, period: TimeSpan.FromSeconds(1))
.Select(_ => DateTime.Now.ToString("HH:mm:ss"));
}
}

not able to fetch links from pagination using watin dll

Hi i am collecting urls using watin framework. i want to traverse all the pages and collect the link and save it in one text file.I dont know how to add the pagination function.here is my code.
using System.Text;
using System.Threading.Tasks;
using WatiN.Core;
namespace magicbricks
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
IE ie = new IE();
ie.GoTo("http://www.99acres.com/property-in-chennai-ffid?search_type=QS&search_location=HP&lstAcn=HP_R&src=CLUSTER&isvoicesearch=N&keyword_suggest=chennai%20%28all%29%3B&fullSelectedSuggestions=chennai%20%28all%29&strEntityMap=W3sidHlwZSI6ImNpdHkifSx7IjEiOlsiY2hlbm5haSAoYWxsKSIsIkNJVFlfMzIsIFBSRUZFUkVOQ0VfUywgUkVTQ09NX1IiXX1d&texttypedtillsuggestion=chennai&refine_results=Y&Refine_Localities=Refine%20Localities&action=%2Fdo%2Fquicksearch%2Fsearch&suggestion=CITY_32%2C%20PREFERENCE_S%2C%20RESCOM_R");
foreach (var currLink in ie.Links)
{
if (currLink.Url.Contains("b"))
{
Console.WriteLine(currLink.Url);
}
}
Console.ReadLine();
}
}
}
any help will be appreciated.
Here is working solution for that. I changed a bit your code.
using System;
using WatiN.Core;
namespace magicbricks
{
static class Class1
{
private static WatiN.Core.Link _nextPageElement;
private static string _firstPartOfAddress = "";
private static string _lastPartOfAddress = "";
private static int _maxPageCounter = 0;
[STAThread]
static void Main(string[] args)
{
IE ie = SetUpBrowser();
EnterFirstWebpage(ie);
ie.WaitForComplete();
LookFoAllLinks(ie);
for (int i = 2; i < _maxPageCounter; i++)
{
Console.WriteLine("----------------------------Next Page {0}---------------------------", i);
Console.WriteLine(AssembleNextPageWebAddress(i));
EnterNextWebpageUrl(ie,AssembleNextPageWebAddress(i));
LookFoAllLinks(ie);
}
Console.ReadKey();
}
private static IE SetUpBrowser()
{
IE ie = new IE();
return ie;
}
private static void EnterFirstWebpage(IE ie)
{
ie.GoTo("http://www.99acres.com/property-in-chennai-ffid?search_type=QS&search_location=HP&lstAcn=HP_R&src=CLUSTER&isvoicesearch=N&keyword_suggest=chennai%20%28all%29%3B&fullSelectedSuggestions=chennai%20%28all%29&strEntityMap=W3sidHlwZSI6ImNpdHkifSx7IjEiOlsiY2hlbm5haSAoYWxsKSIsIkNJVFlfMzIsIFBSRUZFUkVOQ0VfUywgUkVTQ09NX1IiXX1d&texttypedtillsuggestion=chennai&refine_results=Y&Refine_Localities=Refine%20Localities&action=%2Fdo%2Fquicksearch%2Fsearch&suggestion=CITY_32%2C%20PREFERENCE_S%2C%20RESCOM_R");
}
private static void EnterNextWebpageUrl(IE ie,string url)
{
ie.GoTo(url);
ie.WaitForComplete();
}
private static void LookFoAllLinks(IE ie)
{
int currentpageCounter = 0;
var tmpUrl = string.Empty;
const string nextPageUrl = "http://www.99acres.com/property-in-chennai-ffid-page-";
foreach (var currLink in ie.Links)
{
if (currLink.Url.Contains("b"))
{
Console.WriteLine(currLink.Url);
try
{
if (currLink.Name.Contains("nextbutton"))
{
_nextPageElement = currLink;
}
}
catch (Exception ex)
{
}
try
{
if (currLink.GetAttributeValue("name").Contains("page"))
{
_firstPartOfAddress = currLink.Url.Substring(0, nextPageUrl.Length);
tmpUrl = currLink.Url.Remove(0,nextPageUrl.Length);
_lastPartOfAddress = tmpUrl.Substring(tmpUrl.IndexOf("?"));
tmpUrl = tmpUrl.Substring(0,tmpUrl.IndexOf("?"));
int.TryParse(tmpUrl, out currentpageCounter);
if (currentpageCounter > _maxPageCounter)
{
_maxPageCounter = currentpageCounter;
currentpageCounter = 0;
}
}
}
catch (Exception)
{
}
}
}
}
private static string AssembleNextPageWebAddress(int pageNumber)
{
return _firstPartOfAddress + pageNumber + _lastPartOfAddress;
}
}
}
Some explanation :
variable _maxPageCounter contains max numbers of pages to lookfor links.
We are getting this here :
if (currLink.GetAttributeValue("name").Contains("page"))
{
_firstPartOfAddress = currLink.Url.Substring(0, nextPageUrl.Length);
tmpUrl = currLink.Url.Remove(0,nextPageUrl.Length);
_lastPartOfAddress = tmpUrl.Substring(tmpUrl.IndexOf("?"));
tmpUrl = tmpUrl.Substring(0,tmpUrl.IndexOf("?"));
int.TryParse(tmpUrl, out currentpageCounter);
if (currentpageCounter > _maxPageCounter)
{
_maxPageCounter = currentpageCounter;
currentpageCounter = 0;
}
}
Later we are just looping through pages, by create next address.
private static string AssembleNextPageWebAddress(int pageNumber)
{
return _firstPartOfAddress + pageNumber + _lastPartOfAddress;
}
We could use here as well next button, and click it in loop.
I hope it was helpful.

Categories