Pushing to bitbucket with libgit2sharp - c#

I'm trying to use libgit2sharp to push to my repo on bitbucket. I'm trying to do this:
repo.Network.Push(repo.Branches[branchName], pushOptions);
Everything seems fine, no exceptions are thrown and I get no errors in the callback, but when I check on bitbucket none of my commits are there. Other methods seem to work fine (ie I can create a new branch on bitbucket and then use libgit2sharp to fetch and see that I now have that branch locally). Is there anything that I might be missing here?
edit:
Tried to just make a small sample program to see if I can get this working no go. I don't know if my code will help but here it is:
class Program
{
static void Main(string[] args)
{
PushOptions options = new PushOptions();
Credentials creds = new Credentials();
creds.Username = "username";
creds.Password = "password";
options.Credentials = creds;
options.OnPackBuilderProgress = Program.packBuilderProgressHandler;
options.OnPushTransferProgress = Program.pushTransferProgressHandler;
options.OnPushStatusError = Program.pushStatusErrorHandler;
Repository repo = new Repository("E:/Ohad/Work/libgitTest");
repo.Network.Push(repo.Branches["origin/master"], options);
Console.WriteLine("Press enter to close...");
Console.ReadLine();
}
public static bool packBuilderProgressHandler(PackBuilderStage stage, int current, int total)
{
Console.Out.WriteLine("packBuilder => " + current + " / " + total);
return true;
}
public static bool pushTransferProgressHandler(int current, int total, long bytes)
{
Console.Out.WriteLine("pushTransfer => " + current + " / " + total + " , " + bytes);
return true;
}
public static void pushStatusErrorHandler(PushStatusError error)
{
Console.Out.WriteLine("error => " + error.Message);
}
}
Just make a new repo on bitbucket and add the above code (changing the stuff thats hard coded) and it should be reproducible. I just made a random change, added and commited it and then used the program to try to push to bitbucket. The output that I am getting from the above is:
pushTransfer => 0 / 0 , 12
pushTransfer => 0 / 0 , 32
Press enter to close...
The 0/0 looks suspicious to me but I don't know what I'm doing wrong =/. Thanks for any help!!
edit 2:
I just added this:
repo.Branches.Update(repo.Head, delegate(BranchUpdater updater)
{
updater.Remote = "origin";
updater.UpstreamBranch= repo.Head.CanonicalName;
})
to before when I push and it fixed the issue. Not sure exactly why but I'll take it =).

I think that you're willing to push your local master branch rather than the remote tracking one.
repo.Network.Push(repo.Branches["master"], options);
Update:
*The branch 'master' ("refs/heads/master") that you are trying to push does not track an upstream branch. *
Provided you have no "origin" remote, the following should work.
Remote remote = localRepo.Network.Remotes.Add("origin", url);
repo.Branches.Update(repo.Head, -> (A)
b => b.Remote = remote.Name, -> (B)
b => b.UpstreamBranch = repo.Head.CanonicalName); -> (C)
The code above should be read as "The branch pointed at by the HEAD (A) on this local repository will be, by default, configured to track a branch bearing the same name (C) in the distant repository identified by this remote (B)."

Related

Unity Connect to azure Sql Database with AppServices

So I want to connect to my Azure Sql Database using in a unity project,
I used this code provided in the readme of app services Github project:
public class AzureConnect : MonoBehaviour {
private MobileServiceClient _client;
private MobileServiceTable<Score> _table;
// Use this for initialization
void Start () {
_client = new MobileServiceClient("https://myService.azurewebsites.net"); // <- add your app url here.
_table = _client.GetTable<Score>("Score");
ReadItems();
}
private void ReadItems()
{
StartCoroutine(_table.Read<Score>(OnReadItemsCompleted));
}
private void OnReadItemsCompleted(IRestResponse<Score[]> response)
{
if (!response.IsError)
{
Debug.Log("OnReadCompleted: " + response.Url + " data: " + response.Content);//content shows the content of the table properly
Score[] items = response.Data;//Data is always null
Debug.Log("Todo items count: " + items.Length);
}
else
{
Debug.LogWarning("Read Error Status:" + response.StatusCode + " Url: " + response.Url);
}
}
}
The code works perfectly and connects to my DB just fine but for some reason the response DATA is always null although the response CONTENT returns a string with the data in the scores table just fine Any Idea what could be the problem?
PS: the url of the App service is not the real one I use just for demo purpose.
Well I've been struggling with this for hours , and after 6 min of posting the question I figure out the answer so here is the Answer so anyone that faces this problem can know the cause:
The Problem was that I didn't declare my Score Class as [Serializable] as soon as I declared it this way it worked perfectly.

Error: 'The process cannot access the file because it is being used by another process' in Visual Studio c#

I am having some trouble with this error in Visual Studio:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'C:\Users\aheij\Desktop\KinectOutput\swipe.txt' because it is being used by another process.
What I Have tried:
I have tried using these codes obtained from other solved StackOverflow questions similar to mine to try to solve the problem - but even that didn't seem to work?
Ive tried checking if the file is in use, but with no success.
I also run Visual Studio as administrator.
The file is not read-only.
The folder is not open, and the file is not being used in any other program when executing the code - at least not that I can see/know of.
The code:
So, to add some context to my code: I am writing some quick gesture detection code to the Kinect c# BodyBasics SDK v2 code freely available. This is a helper method that I added, that gets called in when a person is in view. If that person is executing the gesture, the method writes the frame time and gesture name to a text file.
Half the time, when the code does work, the gesture recognition works well. However, the other half of the time, the code breaks/stops because the writing to file bit causes the error.
Below is my code to see if the person is standing in the neutral position - its a bit waffly, so apologies about that. I have commented 'ERROR' where the error is (unsurprisingly):
private void Neutral_stance(VisualStyleElement.Tab.Body body, IReadOnlyDictionary<JointType, Joint> joints, IDictionary<JointType, Point> jointPoints, BodyFrame bf)
{
CameraSpacePoint left_hand = joints[JointType.HandLeft].Position;
CameraSpacePoint left_elbow = joints[JointType.ElbowLeft].Position;
CameraSpacePoint left_shoulder = joints[JointType.ShoulderLeft].Position;
CameraSpacePoint left_hip = joints[JointType.HipLeft].Position;
CameraSpacePoint right_hand = joints[JointType.HandRight].Position;
CameraSpacePoint right_elbow = joints[JointType.ElbowRight].Position;
CameraSpacePoint right_shoulder = joints[JointType.ShoulderRight].Position;
CameraSpacePoint right_hip = joints[JointType.HipRight].Position;
double vertical_error = 0.15;
double shoulderhand_xrange_l = Math.Abs(left_hand.X - left_shoulder.X);
double shoulderhand_xrange_r = Math.Abs(right_hand.X - right_shoulder.X);
if (bf != null)
{
TimeSpan frametime = bf.RelativeTime;
string path_p = #"C:\Users\aheij\Desktop\KinectOutput\Punch.txt"; //write to punch file
string path_s = #"C:\Users\aheij\Desktop\KinectOutput\swipe.txt"; //write to swipe file
if (left_hand.Y < left_elbow.Y)
{
if (right_hand.Y < right_elbow.Y)
{
if (shoulderhand_xrange_l < vertical_error)
{
if (shoulderhand_xrange_r < vertical_error)
{
Gesture_being_done.Text = " Neutral";
File.AppendAllText(path_p, frametime.ToString() + " Neutral" + Environment.NewLine); //ERROR
File.AppendAllText(path_s, frametime.ToString() + " Neutral" + Environment.NewLine); //ERROR
}
}
}
}
else
{
Gesture_being_done.Text = " Unknown";
File.AppendAllText(path_p, frametime.ToString() + " Unknown" + Environment.NewLine); //ERROR
File.AppendAllText(path_s, frametime.ToString() + " Unknown" + Environment.NewLine); //ERROR
}
}
}
Any solutions/ideas/suggestions to point me on the right track would be appreciated. I think that it would be good to use the 'using streamwriter' method as opposed to the method I am using here - but I am not sure how? Any help would be appreciated.
Additonal Info: Using Visual Studio 2015; Using windows 10.
Sidenote: I read somewhere that the Windows Search tool in Windows 10 can interfere and cause problems like this so I need to disable it?
As suggested to me I used the Filestream method & ensured the file was closed after use. But, even this still caused the same error.
Thus, I also got rid of having two file-writing actions in rapid succession of each other. I dont know if this is technically right or even true, but based off of this post here: link, my error could be coming up because I am trying to execute the second 'write to text file' line whilst the previous 'write to text file' line is still executing/writing to that same folder & location - hence the clash? Please someone, correct me if I am wrong.
Either way, this seems to have worked.
See below for my edited/corrected method:
private void Neutral_stance(Body body, IReadOnlyDictionary<JointType, Joint> joints, IDictionary<JointType, Point> jointPoints, BodyFrame bf)
{
//cameraspace point joint stuff here again (see original post for this bit leading up to the if statements.)
if (bf != null)
{
TimeSpan frametime = bf.RelativeTime;
string path_s = #"C:\Users\aheij\Desktop\KinectOutput\swipe.txt";
if (left_hand.Y < left_elbow.Y)
{
if (right_hand.Y < right_elbow.Y)
{
if (shoulderhand_xrange_l < vertical_error)
{
if (shoulderhand_xrange_r < vertical_error)
{
Gesture_being_done.Text = " Neutral";
FileStream fs_s = new FileStream(path_s, FileMode.Append); //swipe
byte[] bdatas = Encoding.Default.GetBytes(frametime.ToString() + " Neutral" + Environment.NewLine);
fs_s.Write(bdatas, 0, bdatas.Length);
fs_s.Close();
}
}
}
}
else
{
Gesture_being_done.Text = " Unknown";
FileStream fs_s = new FileStream(path_s, FileMode.Append);
byte[] bdatas = Encoding.Default.GetBytes(frametime.ToString() + " Unknown" + Environment.NewLine);
fs_s.Write(bdatas, 0, bdatas.Length);
fs_s.Close();
}
}
}
Do let me know if there is any way I can make this more elegant or anything else I should be aware of w.r.t this answer.
The code is based off of the code found here: FileStream Tutorial website

Socket connection from Unity to retrieve SUMO's vehicles

I would like to generate a 3D scenario for a traffic simulation.
The main idea would be having SUMO running a simulation and then getting the direction, speed and coordinates (X,Y) from each vehicle, so that I would create 3D models for this cars.
For this purpose, I was thinking about using some kind of TCP/IP communication between Unity and SUMO. Since this is possible while communicating SUMO with a network simulator such as OMNeT++, I was wondering if this would also be possible. I don't need to control the simulation in SUMO from Unity, just retrieve data regarding the vehicles in the network.
Unfortunately, I have no remarkable experience with Unity, so I cannot provide any code trying to achieve this...
EDIT:
As requested, I included some code. However, I only have code in Java.
String configFile = "test/resources/sumo_maps/Test2/Test2.sumo.cfg";
SumoTraciConnection trial = new SumoTraciConnection(configFile,-1);
trial.runServer();
Collection<Vehicle> vehicles = trial.getVehicleRepository().getAll().values();
for(Vehicle car : vehicles){
bw.write(time + " // The vehicle with ID: " + car.getID()+ " is driving "
+ "with a speed of "+ car.getSpeed() + " and is in coordinates x: " +car.getPosition().getX()+
" and y: " + car.getPosition().getY());
bw.newLine();
}
Now, let's proceed to get a bit into the class SumoTraciConnection and its methods. This class is part of the mentioned (in the comments) library Traci4j.
It can be found in GitHub in case you need more info: https://github.com/egueli/TraCI4J/blob/master/src/java/it/polito/appeal/traci/SumoTraciConnection.java
The constructor:
public SumoTraciConnection(String configFile, int randomSeed) {
this.randomSeed = randomSeed;
this.configFile = configFile;
}
Now the runServer() method (I put the one with a boolean argument because if no parameter is given then it is automatically called with a false) Basically, this boolean is used to determine wheter the GUI version of SUMO or the console version will be ran:
public void runServer(boolean withGui) throws IOException, InterruptedException {
retrieveFromURLs(); //Checks if the configFile given has an "http://" at the beggining, in order to download the file
int port = findAvailablePort(); //creates a Socket and finds a port with ServerSocket.getLocalPort()
runSUMO(port, withGui); //It is used to run SUMO with different options, such as the configFile for the simulation, the remote port... sumoProcess is set here as: sumoProcess = Runtime.getRuntime().exec(argsArray);, where argsArray contains the different options mentioned
tryConnect(InetAddress.getLocalHost(), port, sumoProcess); // tryConnect basicaly calls this method tryConnectOnce, which connects as a client to the sumo process mentioned before, and does some checks that everything is correct.
postConnect(); //I will explain this function after
}
postConnect() initialices the DataInput and DataOutput streams and creates the repositories. I show now the relevant parts of the code:
dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
vehicles = new HashMap<String, Vehicle>();
edgeRepo = new Repository.Edges(dis, dos, newIDListQuery(Constants.CMD_GET_EDGE_VARIABLE));
addStepAdvanceListener(edgeRepo);
laneRepo = new Repository.Lanes(dis, dos, edgeRepo, newIDListQuery(Constants.CMD_GET_LANE_VARIABLE));
vehicleListQuery = newIDListQuery(Constants.CMD_GET_VEHICLE_VARIABLE);
addStepAdvanceListener(new StepAdvanceListener() {
public void nextStep(double step) {
vehicleListQuery.setObsolete();
}
});
vehicleListBefore = new HashSet<String>(vehicleListQuery.get());
vehicleRepo = new Repository.Vehicles(dis, dos, edgeRepo, laneRepo, vehicles, vehicleListQuery);
addStepAdvanceListener(vehicleRepo);
Where one StepAdvanceListener is just the following(I cannot explain exactly what is this for but I understand that is something that allow us to realize the new simulationstep has been done, so we have to update the repositories):
//Interface for an object that can be notified when the simulation advances by one step.
public interface StepAdvanceListener {
/**
* Callback for step advancement.
* #param step the new simulation time, in seconds
*/
void nextStep(double step);
}
Up to here, it would be the part related to the connection with SUMO. In the next edit (I need some rest right now..) I'll put the parts related with the Repositories and the Data retrieval
Thanks in advance!

Reporting Services access via Management Studio and a C# application

How do you grant someone access to select Reporting Services from the drop down within Management Studio as per the below image.
Also, I have a colleague who has full admin access to this however when they run the below with the credentials set to DefaultCredentials we seem still be getting an error:
namespace ReportingServicesJobsUtility
{
public class Program
{
public static void Main(string[] args)
{
ListJobSSRS();
}
public static void ListJobSSRS()
{
//create instance of ReportingService2010 called server
server.ReportingService2010 rs = new server.ReportingService2010();
//user credentials running application to be used
rs.Credentials = CredentialCache.DefaultCredentials;
//rs.Credentials = new System.Net.NetworkCredential("","");
//create array of jobs
Job[] jobs = null;
try
{
jobs = rs.ListJobs();
ListRunningJobs(jobs);
}
catch (SoapException e)
{
Console.WriteLine(e.Detail.InnerXml.ToString());
}
Console.ReadLine();
}
//make this a void?
public static bool ListRunningJobs(server.Job[] jobs)
{
int runningJobCount = 0;
Console.WriteLine("Current Jobs");
Console.WriteLine("================================" + Environment.NewLine);
server.Job job = default(server.Job);
foreach (var j in jobs)
{
Console.WriteLine("--------------------------------");
Console.WriteLine("JobID: {0}", job.JobID);
Console.WriteLine("--------------------------------");
Console.WriteLine("Action: {0}", job.JobActionName);
Console.WriteLine("Description: {0}", job.Description);
Console.WriteLine("Machine: {0}", job.Machine);
Console.WriteLine("Name: {0}", job.Name);
Console.WriteLine("Path: {0}", job.Path);
Console.WriteLine("StartDateTime: {0}", job.StartDateTime);
Console.WriteLine("Status: {0}", job.JobStatusName);
Console.WriteLine("Type: {0}", job.JobTypeName);
Console.WriteLine("User: {0}" + Environment.NewLine, job.User);
runningJobCount += 1;
}
Console.Write("There are {0} running jobs. ", runningJobCount);
//returning a true for no reason
return true;
}
}
}
The error message is as follows and we believe this is down to credentials, unless anyone can also shed some light on this?
edit
If I use rs.Credentials = new System.Net.NetworkCredential(#"developmentserver\Administrator","password"); on our development server then this runs with no problems, so it seems that it does not like using DefualtCredentials, either that or mine and my collegue's AD credentials are not sufficient, so back to the original question how do we grant full access to our logons.
Have you tried adding the accounts you want in the Report Manager and setting the role assignment there?
you are asking for advice on two very different issues and i have some idea for the second one only.
you are not describing the layout of the servers involved so i make the assumption that you are on a client machine accessing a webservice that is a bridge to reach a SSRS instance; webservice and SSRS are not on the same machine.
if this is the case then check if you are running into the double hop issue.

C# / Webservice app on server throwing strange exception

We use ADP for employee information. I had to create a small app that called some web services that ADP has to pull employee information. The app is fairly procedural..not really object orientated in a sense. Basically I go through some web services to pull general information, work information, employee status, etc.
I have most of this data writing out to a text file as a log so I can ensure that everything is working correctly. Finally got it all done, and it works perfect on my local machine. Thought I'd just copy the entire structure onto a server and use windows scheduler to schedule the exe to run nightly (once a day). When it tries to run the app it looks like it is dying when it calls the first web service. The task scheduler log says:
""ADP.job" (ADP.exe)
Started 2/11/2010 2:14:34 PM
"ADP.job" (ADP.exe)
Finished 2/11/2010 2:14:38 PM
Result: The task completed with an exit code of (e0434f4d)."
So I checked the event viewer and it says this:
EventType clr20r3, P1 adp.exe, P2 1.0.0.0, P3 4b745bb9, P4 adp, P5 1.0.0.0, P6 4b745bb9, P7 289, P8 2d, P9 system.io.filenotfoundexception, P10 NIL.
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
I put in some console.writelines to see where it is failing...
Here is a simple example of main:
static void Main(string[] args)
{
OpenTextFile();
Console.WriteLine("About to process employee work information...");
tw.WriteLine("About to process employee work information...");
//work info service
EmpWorkInfo();
}
And inside of opentextfile:
public static void OpenTextFile()
{
//used to log data
String sLogName;
Console.WriteLine("Inside of opentextfile");
if (Directory.Exists(logPath))
{
//directory exists
}
else
{
Directory.CreateDirectory(logPath);
}
Console.WriteLine("Inside of opentextfile2");
sLogName = "log_" + DateTime.Today.ToString("MM_dd_yyyy") + ".txt";
tw = new StreamWriter(logPath + sLogName);
}
I see all the console.writelines on the server but as soon as it hits this line from main:
EmpWorkInfo();
Thats when all hell breaks lose (basically it doesn't work). The EmpWorkInfo() is simply a function to get work related information from a web service (as I said this works locally).
static void EmpWorkInfo()
{
Console.Writeline("THIS NEVER PRINTS!!!");
SQLClass s=null;
// Create the web service proxy client.
GetEmployeeWorkInfoService oService = new GetEmployeeWorkInfoService();
oService.Timeout = Int32.MaxValue;
// Serialize the UsernameToken into XML.
// Create the UsernameToken as defined in the WS-I secure profile.
UsernameToken oUsernameToken = new UsernameToken(USERNAME, SECRET);
System.Xml.XmlElement oSecurityHeaderXml =
oUsernameToken.GetXml(new System.Xml.XmlDocument());
ADP.GetEmployeeWorkInfoWebService.SecurityHeaderType oSecurityHeader = new ADP.GetEmployeeWorkInfoWebService.SecurityHeaderType();
oSecurityHeader.Any = new System.Xml.XmlElement[] { oSecurityHeaderXml };
oService.Security = oSecurityHeader;
GetEmployeeWorkInfoRequestFilter oFilter = new GetEmployeeWorkInfoRequestFilter();
//filter by thyssenkrupp company
oFilter.Companies = new String[] { COMPANY_IDENTIFIER };
GetEmployeeWorkInfoRequest oRequest = new GetEmployeeWorkInfoRequest();
oRequest.Filter = oFilter;
try
{
EmployeeWorkInfoType[] arPersonalInfo = oService.GetEmployeeWorkInfo(oRequest);
try
{
s = new SQLClass();
}
catch (Exception e)
{
throw new System.Exception(e.Message.ToString());
}
for (int i = 0; i < arPersonalInfo.Length; i++)
{
String stID = arPersonalInfo[i].EmployeeKey.Identifier.EmployeeId; //employee number
String stEmailAddress = arPersonalInfo[i].WorkInfo.EmailAddress; //employee email address (work)
String stFax = arPersonalInfo[i].WorkInfo.Fax; //employee fax number
DateTime dtHireDate = arPersonalInfo[i].WorkInfo.OriginalHireDate;
String stPhone = arPersonalInfo[i].WorkInfo.Phone; //employee phone number
String stWireless = arPersonalInfo[i].WorkInfo.Wireless; //employee wireless number
tw.WriteLine("Processing ID:" + stID + " Email Work: " + stEmailAddress + " Fax Work: " + stFax + " Hire Date: " + dtHireDate + " Phone Work: " + stPhone + " Wireless Work: " + stWireless + ".");
Console.WriteLine("Processing ID:" + stID + " Email Work: " + stEmailAddress + " Fax Work: " + stFax + " Hire Date: " + dtHireDate + " Phone Work: " + stPhone + " Wireless Work: " + stWireless + ".");
s.SetSQLCommand("dbo.ADP_uiEmployeeWorkInfo");
s.AddSQLCmdParameter("#EmployeeNumber", System.Data.SqlDbType.VarChar, stID);
s.AddSQLCmdParameter("#EmailAddress", System.Data.SqlDbType.VarChar, stEmailAddress);
s.AddSQLCmdParameter("#Fax", System.Data.SqlDbType.VarChar, stFax);
s.AddSQLCmdParameter("#HireDate", System.Data.SqlDbType.DateTime, dtHireDate);
s.AddSQLCmdParameter("#Telephone", System.Data.SqlDbType.VarChar, stPhone);
s.AddSQLCmdParameter("#Mobile", System.Data.SqlDbType.VarChar, stWireless);
s.SQLExecuteNonQuery();
Console.WriteLine("Processed ID:" + stID + " Email Work: " + stEmailAddress + " Fax Work: " + stFax + " Hire Date: " + dtHireDate + " Phone Work: " + stPhone + " Wireless Work: " + stWireless + ".");
Console.WriteLine(Environment.NewLine);
}
s.CloseSQLDB();
s.Dispose();
}
//catch any exception from adp side.
catch (Exception e)
{
throw new System.Exception(e.Message.ToString());
}
}
This functions code is irrelevant (its ugly but do not let that bother you, the code works...). My issue is I cannot even get to the first console.writeline of that function. Is there anything special I need to do when it comes to working with webservices?
Edit
Logpath is defined as simply a static string outside of main:
private static string logPath = Environment.CurrentDirectory + "\\log\\";
I suspect that your application is not able to load the types referenced in that function - EmpWorkInfo.
1) Can you run this application on the target server in a commannd window (cmd.exe) ?
2) Are you using any assemblies from ADP that are installed in the global assembly cache (GAC)? Run "gacutil -l" on your localmachine to see if you are using any assemblies from ADP that are installed in thr gac. If they are, you will need to install these into the machine on which you are running the app.
Does logPath have a trailing backslash? Either way, you ought to use Path.Combine, rather than the string catenation operator (+).
What happens if you comment out all the code in EmpWorkInfo() apart from the first Console.Writeline? Does it still not get written out?
Found out I need the Microsoft.Web.Services3 dll installed on the server.
Continuation on "feroze" answer;
If you want to figure out if the 'loading of dependencies' is causing you grief here, i suggest using the "FUSLOGVW.EXE" tool *(part of .Net). When you run this it will give you a little dialog window with a few options. Create a directory somewhere (like "c:\temp\fusion_logs"), set the mode of FUSLOGVW to "log bind failures only", "custom location->c:\temp\fusion_logs".
Now restart your application and check that it failed. Now look into your fusion_logs directory. This should give you sub directories with different (maybe only 1 for now) application names. Inside each directory you will find the log files. These log files contain the "failed assembly loads" and who (which calling assembly) caused them.
They might help your hunt for a working application,
Hope this helps,
Edit: Posted this after you found the cause. The fuslogvw.exe would have shown you the missing assembly.

Categories

Resources