Download one file from remote (git show) using libgit2sharp - c#

Using git show, I can fetch the contents of a particular file from a particular commit, without changing the state of my local clone:
$ git show <file>
$ git show <commit>:<file>
How can I achieve this programatically using libgit2sharp?

According to the documentation:
$ git show 807736c691865a8f03c6f433d90db16d2ac7a005:a.txt
Is equivalent to the code below:
using System;
using System.IO;
using System.Linq;
using System.Text;
using LibGit2Sharp;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
var pathToFile = "a.txt";
var commitSha = "807736c691865a8f03c6f433d90db16d2ac7a005";
var repoPath = #"path/to/repo";
using (var repo =
new Repository(repoPath))
{
var commit = repo.Commits.Single(c => c.Sha == commitSha);
var file = commit[pathToFile];
var blob = file.Target as Blob;
using (var content = new StreamReader(blob.GetContentStream(), Encoding.UTF8))
{
var fileContent = content.ReadToEnd();
Console.WriteLine(fileContent);
}
}
}
}
}

As nulltoken says in the comments, Lookup<T>() can use colon-pathspec syntax.
using (var repo = new Repository(repoPath))
{
// The line below is the important one.
var blob = repo.Lookup<Blob>(commitSha + ":" + path);
using (var content = new StreamReader(blob.GetContentStream(), Encoding.UTF8))
{
var fileContent = content.ReadToEnd();
Console.WriteLine(fileContent);
}
}
The tagged line is the change from Andrzej Gis's answer. It replaces the commit =, file =, and blob = lines. Also, commitSha can be any refspec: v3.17.0, HEAD, origin/master, etc.

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");

NAudio looking for a way to read from a Stream when changing pitch instead of a File

I am using the Naudio lib in my project and I've used it already to combine MP3 files and use them.
I combined them using Mp3FileReader(Stream), so it is possible to read from a stream with this object but when I try to change the audio pitch and follow their tutorial this is how it goes:
using (var reader = new MediaFoundationReader(inPath)) //only reads from file
{
var pitch = new SmbPitchShiftingSampleProvider(reader.ToSampleProvider());
using(var device = new WaveOutEvent())
{
pitch.PitchFactor = (float)upOneTone; // or downOneTone
// just playing the first 10 seconds of the file
device.Init(pitch.Take(TimeSpan.FromSeconds(10)));
device.Play();
while(device.PlaybackState == PlaybackState.Playing)
{
Thread.Sleep(500);
}
}
}
now my problem is that MediaFoundationReader only reads from file, is there another way to load from a stream and change the pitch/ frequency.
any help will be appreciated.
I hope this code will help you:
This function receive a Stream instead a file path.
using System;
using System.IO;
using System.Threading;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
namespace Test
{
public class HelpOnStackOverFlow
{
public static void PlayShift(Stream stream)
{
var fr = new Mp3FileReader(stream);
fr.ToSampleProvider();
var pitch = new SmbPitchShiftingSampleProvider(fr.ToSampleProvider());
var rates = new float[] { 1.0594630943593f, 1.12246204830937f, 1.18920711500272f, 1.25992104989487f };
foreach (var rate in rates)
{
var device = new WaveOutEvent();
pitch.PitchFactor = rate;
device.Init(pitch.Take(TimeSpan.FromSeconds(1)));
device.Play();
Thread.Sleep(1000);
}
}
}
}

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.

C# Reqex for new line followd by char and 10 digits

My issue is:
I have a file about 100 Mb that I've tried to read line by line and the do some processing. The performance was not very good. That's why I want now to change and read it in memory at once by using ReadAllLines() and then spliting it in some reports that are marked by a line containing T followed by 10 digits. Can someone help me with generating the right regular expression that I can use to split, I am thinking of something like:
#"(\n|\r|\r\n)[T](?<!\d)\d{10}(?!\d)",
is this correct? Thanks in advance!
A split pattern for your case could look like this:
(?=\DT\d{10}\D)
Code Sample:
using System;
using System.Text.RegularExpressions;
class Test
{
static void Main(string[] args)
{
String sourcestring = #"sdfso dadfjlsdfjksdjfkjsd
sdfso dadfjlsdfjksdjfkjsd
T1234567898dssdkfjskfjksdj
T1234567890dssdkfjskfjksdj
sdfso dadfjlsdfjksdjfkjsd
T1234567891dssdkfjskfjksdj";
String matchpattern = #"(?=\DT\d{10}\D)";
Regex re = new Regex(matchpattern);
String[] splitarray = re.Split(sourcestring);
for(int sIdx = 0; sIdx < splitarray.Length; sIdx++ ) {
Console.WriteLine("[{0}] = {1}", sIdx, splitarray[sIdx].Trim());
}
}
}
Depending on your context you are probably still better off reading a large file line by line and collection the individual reports/blocks in a List or the like as suggested by Wiktor. You could also further processing of the reports/blocks in parallel. I suggest making use of the StreamReader and StringBuilder classes.
Sample implementation
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string pattern = #"^T\d{10}\D";
var re = new Regex(pattern);
var result = new List<string>();
var block = new StringBuilder();
var fileStream = new FileStream(#"c:\file.txt", FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
if (re.IsMatch(line))
{
//store current block or hand it off to different process, etc.
result.Add(block.ToString());
block.Clear();
}
block.AppendLine(line);
}
// final block
result.Add(block.ToString());
}
}
}

Ghostscript.NET.dll print pdf to specified printer

How to print pdf using ghostscript api.
I tried google but still not getting proper solution. Please help me how i do this task.
This should work for you (by using Ghostscript.NET wrapper):
using System;
using System.Collections.Generic;
using Ghostscript.NET.Processor;
namespace Ghostscript.NET.Samples
{
public class SendToPrinterSample : ISample
{
public void Start()
{
// YOU NEED TO HAVE ADMINISTRATOR RIGHTS TO RUN THIS CODE
string printerName = "YourPrinterName";
string inputFile = #"E:\__test_data\test.pdf";
using (GhostscriptProcessor processor = new GhostscriptProcessor())
{
List<string> switches = new List<string>();
switches.Add("-empty");
switches.Add("-dPrinted");
switches.Add("-dBATCH");
switches.Add("-dNOPAUSE");
switches.Add("-dNOSAFER");
switches.Add("-dNumCopies=1");
switches.Add("-sDEVICE=mswinpr2");
switches.Add("-sOutputFile=%printer%" + printerName);
switches.Add("-f");
switches.Add(inputFile);
processor.StartProcessing(switches.ToArray(), null);
}
}
}
}

Categories

Resources