I am trying to make an interface between my code and my personal gihub repo and my current issue is that I need to be able to automatically make calls to rewrite the data of a github file. However the main article which has helped me write this code, as well as the github OctoKit docs claim I need the file's sha key in order to make any changes to it.
These are all of my imports currently:
using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System; using System.Collections.Generic; using System.Windows.Forms; using System.IO.Packaging; using System.Net; using System.IO; using Octokit; using System.Text;
I have tried in-depth research through the .Net docs as well as the OctoKit docs and digging through the attributes of every single line. Nothing has yielded any clues as to how to find the sha of a github file. The main article I was following used this line to get the sha, fileDetails.First().sha and 'fileDetails' is created using this line: var fileDetails = gitHubClient.Repository.Content.GetAllContentsByRef(owner, repoName,filePath, branch); however, for Visual Studio 2019, it throws a CS1061 Error claiming this data type cannot have First() applied to it.
My code is below for this specific problem. If you know anything thank you very much for your time. If not thanks for a visit. Again if anyone has any insight to fixing this I am in debt to you truly.
`private void write_new_announcements_to_website(string websiteurl, string newAnnouncements) {
GitHubClient gitHubClient = new GitHubClient(new ProductHeaderValue("jerry-spice.github.io"));
gitHubClient.Credentials = new Credentials("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");
var sb = new StringBuilder("");
sb.AppendLine(newAnnouncements);
var (owner, repoName, filePath, branch) = ("Jerry-Spice", "jerry-spice.github.io",
websiteurl, "main");
/*gitHubClient.Repository.Content.CreateFile(
owner, repoName, filePath,
new CreateFileRequest($"Updated info for {filePath}", sb.ToString(), branch));*/
var fileDetails = gitHubClient.Repository.Content.GetAllContentsByRef(owner, repoName,filePath, branch);
//Console.WriteLine(fileDetails)
var updateResult = gitHubClient.Repository.Content.UpdateFile(owner, repoName, filePath,
new UpdateFileRequest("My updated file", sb.ToString(), fileDetails.First().sha));
}
`
The problem is GetAllContentsByRef returns as Task. You'll need to await the call to get the data. Also, the SHA property is proper case. See the following changes.
GitHubClient gitHubClient = new GitHubClient(new ProductHeaderValue("jerry-spice.github.io"));
gitHubClient.Credentials = new Credentials("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");
var sb = new StringBuilder("");
sb.AppendLine(newAnnouncements);
var (owner, repoName, filePath, branch) = ("Jerry-Spice", "jerry-spice.github.io",
websiteurl, "main");
/*gitHubClient.Repository.Content.CreateFile(
owner, repoName, filePath,
new CreateFileRequest($"Updated info for {filePath}", sb.ToString(), branch));*/
var fileDetails = await gitHubClient.Repository.Content.GetAllContentsByRef(owner, repoName,filePath, branch);
//Console.WriteLine(fileDetails)
var updateResult = gitHubClient.Repository.Content.UpdateFile(owner, repoName, filePath,
new UpdateFileRequest("My updated file", sb.ToString(), fileDetails.First().Sha));
Related
I am trying to access the macros inside of an Access database (accdb).
I tried using:
using Microsoft.Office.Interop.Access.Dao;
...
DBEngine dbe = new DBEngine();
Database ac = dbe.OpenDatabase(fileName);
I found a container["Scripts"] that had a document["Macro1"] which is my target. I am struggling to access the contents of the document. I also question if the Microsoft.Office.Interop.Access.Dao is the best reference for what I am trying to achieve.
What is the best way to view the content of the macros and modules?
You can skip the DAO part, it's not needed in this case. Macros are project specific, so in order to get them all, you would need to loop through your projects. In my example, i just have one project.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Access;
namespace Sandbox48
{
public class Program
{
public static void Main(string[] args)
{
Microsoft.Office.Interop.Access.Application oAccess = null;
string savePath = #"C:\macros\";
oAccess = new Microsoft.Office.Interop.Access.Application();
// Open a database in exclusive mode:
oAccess.OpenCurrentDatabase(
#"", //filepath
true //Exclusive
);
var allMacros = oAccess.CurrentProject.AllMacros;
foreach(var macro in allMacros)
{
var fullMacro = (AccessObject)macro;
Console.WriteLine(fullMacro.Name);
oAccess.SaveAsText(AcObjectType.acMacro, fullMacro.FullName, $"{savePath}{ fullMacro.Name}.txt");
}
Console.Read();
}
}
}
I upgraded my old application in .Net 4.5. There are some obsolete methods warnings I was getting so thought to resolve them. One of the obsolete methods is XmlValidatingReader.
Looked up on the internet and found that XmlReaderSettings is a potential alternate of XmlValidatingReader.
// ==old code==
Hashtable _SchemasCache = new Hashtable();
XmlReader xmlReader = new XmlTextReader(xmlStream);
XmlValidatingReader validatingReader = new XmlValidatingReader(xmlReader);
validatingReader.Schemas.Add(root.Namespace, schemaLocation); // both parametres are string. No error
_SchemasCache.Add(schemaLocation, validatingReader.Schemas);
// ==new code==
var schemaLocation = "res://somepath/Messages.xsd";
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(root.Namespace, schemaLocation); // this line gives error
_SchemasCache.Add(schemaLocation, settings.Schemas);
old code doesn't give any error but the new code gives an error of The URI prefix is not recognized. I couldn't find the reason for this behavior of settings.Schemas.Add(), as it is working fine with XmlValidatingReader. Can anyone help with this?
Edit: Here value of schemaLocation is "res://somepath/Messages.xsd". Because schemaLocation has no Http: or https:// or not a local resource, that is why the error is occurring. How can I add schemas with these values using XmlReaderSettings
Edit 2: as this XSD is an embedded resource, I found some code online for this scenario. I made below code changes.
Assembly asm = Assembly.Load("AssemblyNameWhereXSDis");
Uri uri = new Uri(#"res://p.a.t.h/Autorisatie/Messages.xsd");
string resourceName1 = asm.GetName().Name + uri.AbsolutePath.Replace("/", ".");
using (Stream schemaStream = myAssembly.GetManifestResourceStream(resourceName1))
{
using (XmlReader schemaReader = XmlReader.Create(schemaStream)) // this line gives error : value(schemaStream) cannot be null
{
settings.Schemas.Add(root.Namespace, schemaReader);
}
}
here, the value of schemaStream is null. And the value of resourceName1 is assemblyname.folder.Message.xsd.
I have made Message.xsd as Embedded Resource from Visual Studio but still not working.
Source of issue
As you figured yourself - URI has to point to a REAL file somewhere - either a URL (HTTP/HTTPS) or a local file ("C:\...").
So, if you prefer using an Embedded Resource instead, you need to use a fully-specified path in the following form:
"Namespace.FolderName.Filename.Extension"
Example
using System;
using System.Linq;
using System.Reflection;
using System.Xml;
// ...
// get full resourceName from current assembly using Linq
var messagesResourceFullName = Assembly.GetExecutingAssembly()
.GetManifestResourceNames()
.Where(n => n.EndsWith("Messages.xsd"));
using (var schemaStream = asm.GetManifestResourceStream(messagesResourceFullName))
{
if (schemaStream == null) throw new FileNotFoundException();
using (var schemaReader = XmlReader.Create(schemaStream))
{
settings.Schemas.Add(root.Namespace, schemaReader);
}
}
source
Add this line in your code :
using System.Linq;
I have a WPF C# application that contains a button.
The code of the button click is written in separate text file which will be placed in the applications runtime directory.
I want to execute that code placed in the text file on the click of the button.
Any idea how to do this?
Code sample for executing compiled on fly class method:
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Net;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string source =
#"
namespace Foo
{
public class Bar
{
public void SayHello()
{
System.Console.WriteLine(""Hello World"");
}
}
}
";
Dictionary<string, string> providerOptions = new Dictionary<string, string>
{
{"CompilerVersion", "v3.5"}
};
CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
CompilerParameters compilerParams = new CompilerParameters
{GenerateInMemory = true,
GenerateExecutable = false};
CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
if (results.Errors.Count != 0)
throw new Exception("Mission failed!");
object o = results.CompiledAssembly.CreateInstance("Foo.Bar");
MethodInfo mi = o.GetType().GetMethod("SayHello");
mi.Invoke(o, null);
}
}
}
You can use Microsoft.CSharp.CSharpCodeProvider to compile code on-the-fly. In particular, see CompileAssemblyFromFile.
I recommend having a look at Microsoft Roslyn, and specifically its ScriptEngine class.
Here are a few good examples to start with:
Introduction to the Roslyn Scripting API
Using Roslyn ScriptEngine for a ValueConverter to process user input.
Usage example:
var session = Session.Create();
var engine = new ScriptEngine();
engine.Execute("using System;", session);
engine.Execute("double Sin(double d) { return Math.Sin(d); }", session);
engine.Execute("MessageBox.Show(Sin(1.0));", session);
Looks like someone created a library for this called C# Eval.
EDIT: Updated link to point to Archive.org as it seems like the original site is dead.
What you need is a CSharpCodeProvider Class
There are several samples to understand how does it work.
1 http://www.codeproject.com/Articles/12499/Run-Time-Code-Generation-I-Compile-C-Code-using-Mi
The important point of this example that you can do all things on flay in fact.
myCompilerParameters.GenerateExecutable = false;
myCompilerParameters.GenerateInMemory = false;
2 http://www.codeproject.com/Articles/10324/Compiling-code-during-runtime
This example is good coz you can create dll file and so it can be shared between other applications.
Basically you can search for http://www.codeproject.com/search.aspx?q=csharpcodeprovider&x=0&y=0&sbo=kw&pgnum=6 and get more useful links.
I have a WPF C# application that contains a button.
The code of the button click is written in separate text file which will be placed in the applications runtime directory.
I want to execute that code placed in the text file on the click of the button.
Any idea how to do this?
Code sample for executing compiled on fly class method:
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Net;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string source =
#"
namespace Foo
{
public class Bar
{
public void SayHello()
{
System.Console.WriteLine(""Hello World"");
}
}
}
";
Dictionary<string, string> providerOptions = new Dictionary<string, string>
{
{"CompilerVersion", "v3.5"}
};
CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
CompilerParameters compilerParams = new CompilerParameters
{GenerateInMemory = true,
GenerateExecutable = false};
CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
if (results.Errors.Count != 0)
throw new Exception("Mission failed!");
object o = results.CompiledAssembly.CreateInstance("Foo.Bar");
MethodInfo mi = o.GetType().GetMethod("SayHello");
mi.Invoke(o, null);
}
}
}
You can use Microsoft.CSharp.CSharpCodeProvider to compile code on-the-fly. In particular, see CompileAssemblyFromFile.
I recommend having a look at Microsoft Roslyn, and specifically its ScriptEngine class.
Here are a few good examples to start with:
Introduction to the Roslyn Scripting API
Using Roslyn ScriptEngine for a ValueConverter to process user input.
Usage example:
var session = Session.Create();
var engine = new ScriptEngine();
engine.Execute("using System;", session);
engine.Execute("double Sin(double d) { return Math.Sin(d); }", session);
engine.Execute("MessageBox.Show(Sin(1.0));", session);
Looks like someone created a library for this called C# Eval.
EDIT: Updated link to point to Archive.org as it seems like the original site is dead.
What you need is a CSharpCodeProvider Class
There are several samples to understand how does it work.
1 http://www.codeproject.com/Articles/12499/Run-Time-Code-Generation-I-Compile-C-Code-using-Mi
The important point of this example that you can do all things on flay in fact.
myCompilerParameters.GenerateExecutable = false;
myCompilerParameters.GenerateInMemory = false;
2 http://www.codeproject.com/Articles/10324/Compiling-code-during-runtime
This example is good coz you can create dll file and so it can be shared between other applications.
Basically you can search for http://www.codeproject.com/search.aspx?q=csharpcodeprovider&x=0&y=0&sbo=kw&pgnum=6 and get more useful links.
Discussion on OOoForum.org
In python, using pyuno, I can do it like this:
table = self.model.createInstance("com.sun.star.text.TextTable")
This doesn't seem to work in C#. Here is my test code (I realize I probably don't need all those using statements, but I am adapting someone else's code):
using System;
using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.uno;
using unoidl.com.sun.star.bridge;
using unoidl.com.sun.star.frame;
using unoidl.com.sun.star.document;
using unoidl.com.sun.star.text;
using unoidl.com.sun.star.container;
using unoidl.com.sun.star.util;
using unoidl.com.sun.star.table;
using unoidl.com.sun.star.beans;
namespace FromScratch
{
class MainClass
{
public static void Main(string[] args)
{
XComponentContext componentContext =
uno.util.Bootstrap.bootstrap();
XMultiServiceFactory multiServiceFactory = (XMultiServiceFactory)
componentContext.getServiceManager();
XTextDocument document;
XComponentLoader loader = (XComponentLoader)
multiServiceFactory.createInstance
("com.sun.star.frame.Desktop");
document = (XTextDocument) loader.loadComponentFromURL
("private:factory/swriter", "_blank", 0,
new PropertyValue[0]);
XText text = document.getText();
XTextCursor cursor = text.createTextCursor();
XTextTable table = (XTextTable)
multiServiceFactory.createInstance
("com.sun.star.text.TextTable");
table.initialize(2, 2);
text.insertTextContent(cursor, table, false);
}
}
}
Most of it seems to work fine, but when it gets to this line:
table.initialize(2, 2);
I get a runtime error:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object
at FromScratch.MainClass.Main (System.String[] args) [0x00063] in /home/matthew/Desktop/OpenOfficeSample/FromScratch/Main.cs:37
Apparently, this line:
XTextTable table = (XTextTable)
multiServiceFactory.createInstance
("com.sun.star.text.TextTable");
doesn't actually set table to anything.
What is going on here?
Solution (from OOoForum.org):
You must get the text table from the document multiservice factory, not from the multiservice factory of the service manager. You can do this by casting your document (a Model) to XMultiServiceFactory and calling its createInstance method.
XTextTable table = (XTextTable)
((XMultiServiceFactory)document).createInstance
("com.sun.star.text.TextTable");
See DevGuide.