I cannot call methods in c# - visual-studio

I picked up a project recently...
I cannot call methods in C #.
Did some setting in Visual Studio? I'm using Visual Studio 2012 Express.
Look my code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Web.Classes;
namespace Web.Business
{
public class TicketDB
{
Random r = new Random();
r.Next(4); // Error
}
}

You have to define a method first. Just a class is not enough.
Here is an example with a Main() method, but you can use another method (or even constructor) as well:
private static void Main()
{
Random r = new Random();
r.Next(4);
}

Your Class code should more be like that:
public class TicketDB
{
int rNum = 0;
// Constructor - called when created
public TicketDB()
{
Random r = new Random();
rNum = r.Next(4); // Error
}
}

Could. I was forgetting to call within the method. My fault.
Thanks for the help. Helped me remember the OOP.

Related

Visual studio how to add custom tool/code generator configuration options

I wanted to easily turn some json schema files into classes. So googling I found NJsonSchema and I implemented this in a visual studio custom tool so I can set this on relevant json files and get my classes out. This al works and I pasted the code below. This code comes from this very answer. Though it does need a little updating for VS2022.
I find that documentation on how to do this is rather rare and the thing I am missing is how I can add something like configuration options for the custom tool.
Take for example the line "ClassStyle = CSharpClassStyle.Record," that is something one might want configurable for the user. But I cannot find anything on how to do that. Anyone have a good pointer/answer on this?
Preferably a way to add take the config from some custom properties in the file its properties that are available when the custom tool is configured on a project file.
using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System.Text;
using NJsonSchema.CodeGeneration.CSharp;
using NJsonSchema;
namespace ClassGeneratorForJsonSchema
{
[PackageRegistration(UseManagedResourcesOnly = true)]
[InstalledProductRegistration("GenerateClassesFromJsonSchema", "Use NJsonSchema to generate code from a json schema.", "1.0")]
[Guid("202E7E8B-557E-46CB-8A1D-3024AD68F44A")]
[ComVisible(true)]
[ProvideObject(typeof(ClassGeneratorForJsonSchema))]
[CodeGeneratorRegistration(typeof(ClassGeneratorForJsonSchema), "ClassGeneratorForJsonSchema", "{FAE04EC1-301F-11D3-BF4B-00C04F79EFBC}", GeneratesDesignTimeSource = true)]
public sealed class ClassGeneratorForJsonSchema : IVsSingleFileGenerator
{
#region IVsSingleFileGenerator Members
public int DefaultExtension(out string pbstrDefaultExtension)
{
pbstrDefaultExtension = ".cs";
return pbstrDefaultExtension.Length;
}
public int Generate(string wszInputFilePath, string bstrInputFileContents,
string wszDefaultNamespace, IntPtr[] rgbOutputFileContents,
out uint pcbOutput, IVsGeneratorProgress pGenerateProgress)
{
try
{
var schema = JsonSchema.FromJsonAsync(bstrInputFileContents).Result;
var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings()
{
JsonLibrary = CSharpJsonLibrary.SystemTextJson,
ClassStyle = CSharpClassStyle.Record,
Namespace = wszDefaultNamespace
});
byte[] bytes = Encoding.UTF8.GetBytes(generator.GenerateFile());
int length = bytes.Length;
rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(length);
Marshal.Copy(bytes, 0, rgbOutputFileContents[0], length);
pcbOutput = (uint)length;
}
catch (Exception ex)
{
pcbOutput = 0;
}
return VSConstants.S_OK;
}
#endregion
}
}

Does Linq Select does not work with IList?

I'm working with Visual Studio 2019 and it suggested a conversion for a foreach to Linq which then doesn't compile:
using System.Collections;
using System.Collections.Generic;
using System.Linq;
static void Main(string[] args)
{
var list = new List<object>();
list.Add("One");
list.Add("Two");
list.Add("Three");
// To make the point...
var iList = (IList)list;
// This doesn't compile and generates CS1061: IList does not contain a definition for Select.
// I thought Linq gave Select to list types?
var toStringList = iList.Select(s => s.ToString());
// The original foreach version:
var outputList = new List<string>();
foreach (var item in iList)
{
var itemToString = item.ToString();
outputList.Add(itemToString);
}
}
Linq is a set of extension methods on everything that implements IEnumerable<T>.
The non-generic IList doesn't implement that interface, so Linq won't work on it.
Visual Studio 2019 Professional with ReSharper doesn't suggest Select for me:

Scrape a table using ScrapySharp and HtmlAgilityPack

I am trying to scrape an economic calendar from a specific website. Actually, I tried many times without any success, I don't know where I am wrong. Can you help me, pls?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using ScrapySharp.Extensions;
using ScrapySharp.Network;
namespace Calendar
{
class Program
{
static void Main(string[] args)
{
var url = "https://www.fxstreet.com/economic-calendar";
var webGet = new HtmlWeb();
if (webGet.Load(url) is HtmlDocument document)
{
var nodes = document.DocumentNode.CssSelect("#fxst-calendartable tbody").ToList();
foreach (var node in nodes)
{
// event_time
Debug.Print(node.CssSelect("div div").Single().InnerText);
// event-title
Debug.Print(node.CssSelect("div a").Single().InnerText);
}
}
Console.WriteLine("");
Console.ReadLine()
}
}
}
What error are you getting?
If you want to publish the event names and times from the website, I am assuming you need to read the table.
You can do so using
HtmlNode tablebody = doc.DocumentNode.SelectSingleNode("//table[#class='fxs_c_table']/tbody");
foreach(HtmlNode tr in tablebody.SelectNodes("./tr[#class='fxs_c_row']"))
{
Console.WriteLine("\nTableRow: ");
foreach(HtmlNode td in tr.SelectNodes("./td"))
{
Console.WriteLine(td.SelectSingleNode("./span").InnerText);
}
}
Get hold of the table with the class attribute and then use relevant XPATH to traverse the elements. Please post the error you are getting with your code.

Strange: Entity framework (code first) slower and behave strangly with generic repository

We have a generic repository done with code-first technique. As the code is in testing we realized that the generic repository is relatively slower than that of directly accessing the DBContext and loading data. In order to simulate the issue for you all, we simplify the generic repository wrote a new code and that code is pasted below..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DemoTest.Bll.Models;
using DemoTest.Bll.DB;
using MasIt.Common.BackEnd;
using System.Data.Entity;
namespace DemoTest.Bll.Handlers
{
public abstract class MyHandlerBase<E, T>
where E : DbSet<T>
where T : class, IBaseObject
{
public MyHandlerBase(E mySet)
{
dbSet = mySet;
}
public E dbSet;
protected IEnumerable<T> GetAllNew(Func<T, bool> predicate)
{
try
{
return dbSet.Where(predicate).AsEnumerable();
}
catch { return null; }
}
}
public class StudentHandler : MyHandlerBase<DbSet<Student>, Student>
{
public StudentHandler()
:base(DemoDBContext.GetContext().Students)
{
//_entitySet = new DemoDBContext().Students;
}
public List<Student> getList(bool option1)
{
if (option1)
{
// Option 1 this is very fast and hit the Student Constructor only once
IEnumerable<Student> response1 = this.dbSet.Where(x => x.StudentId == 10).AsEnumerable();
return response1.ToList();
}
else
{
// Option 2 this is very slow and hit the Student Constructor the student record count of the table
IEnumerable<Student> response2 = this.GetAllNew(x => x.StudentId == 10);
return response2.ToList();
}
}
}
}
Can anybody say why Option 2 is slower.. it is not just slow, it hits the Student class constructor many times, while option 1 hits the constructor only once.. So it seems to us that option 1 load only the matching record, where as option 2 load all the records and match them in memory to filter records..
Generic Repository is a must.. Any fix is highly appreciated...
Got the fix...
Replacing
"Func<T, bool> predicate" with
"Expression<Func<E, Boolean>>" predicate did the trick..
Man .. a horrible nightmare is just over..

Odd bug in C#4 compiler? Alias namespaces getting mixed up

Here's my issue,
I'm using a namespace to remove ambiguity from a factory class which is creating domain objects from entity framework entity objects (a POCO factory,.. if that makes sense!). Call me old fashioned but I like things this way :-)
The namespaces I'm working with are aliased as such -
using Entities = DataAccess.Models.AccessControl;
using Cases = DomainModel.BusinessObjects.Implimentations.Cases;
Now, the DomainModel.BusinessObjects.Implimentations.Cases namespace only has one type so far called CaseType. However whilst I was working on another type which consumes the CaseType class I noticed that when I 'dot' into the Cases alias, it points to a totally different namespace in my DataAccess assembly and gives me the CaseTypeFactory in intellisense.
So I checked the CaseType and CaseTypeFactory classes and they are namespaced correctly. What in god's name is going on? I really can't work this one out.
Here's the code for the CaseType and CaseTypeFactory if it helps.
CaseTypeFactory
using Domain = DomainModel.BusinessObjects.Implimentations.Cases;
using Entities = DataAccess.Models.AccessControl;
using Interfaces.DataAccess;
namespace DataAccess.Factories.Cases
{
public class CaseTypeFactory :
IEntityPOCOFactory<Domain.CaseType, Entities.CaseType>
{
#region IEntityPOCOFactory<CaseType,CaseType> Members
public Domain.CaseType CreatePOCO(Entities.CaseType entity)
{
return new Domain.CaseType(entity.Id, entity.Name, entity.LastChanged);
}
public IList<Domain.CaseType> CreatePOCOs(
IEnumerable<Entities.CaseType> entities)
{
var toReturn = new List<Domain.CaseType>();
foreach (var entity in entities)
{
toReturn.Add(CreatePOCO(entity));
}
return toReturn;
}
#endregion
}
}
CaseType
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DomainModel.BusinessObjects.Base;
namespace DomainModel.BusinessObjects.Implimentations.Cases
{
public class CaseType : NamedNumberedAndVersioned
{
public CaseType(string name, DateTime lastChanged)
: this(0, name, lastChanged) { }
public CaseType(int id, string name, DateTime lastChanged)
: base(id, name, lastChanged) { }
public void Update(string name)
{
this.Name = name;
}
}
}
It's probably worth mentioning I'm working with .Net 4.0 / VS2010
Any help would be massively appreciated.
Thanks in advance.
Is the code you're writing in the DataAccess.Factories namespace? If so, then Cases will indeed resolve to DataAccess.Factories.Cases first.
Two options:
Use an alias which isn't also the name of another namespace, e.g.
using DomainCases = ...
Use :: instead of . to force it to use the alias:
IEntityPOCOFactory<Cases::CaseType, Whatever>
I'd personally go for the first option to make things clearer... or try to avoid requiring namespace aliases to start with.

Resources