LogParser crashes without error in C# - c#

I'm trying to implement MS LogParser in a C# application. This compiles fine but inexplicably crashes on the logQuery.ExecuteBatch() method. The try/catch block doesn't catch it unless I specifically malform the szQuery, which suggests that everything is working as it should, I'm just not getting any output.
Any thoughts on why it might be crashing or where I might find some logging?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FolderLoggingLib;
using MSUtil;
namespace ConsoleApplication20
{
class Program
{
static void Main(string[] args)
{
//refLog = new BinaryInputFormat();
LogQueryClass logQuery = new LogQueryClass();
ICOMCSVOutputContext output = new COMCSVOutputContextClass();
ILogParserInputContext parse = new BinaryInputFormat();
string szFileName = #"E:\Programming\FolderLogging\2012-05-13.fbl";
string szQuery = "SELECT Folder, User, Record, DB, TO_LOCALTIME(Timestamp) AS DateTime, Operation, Checked FROM " + szFileName + " ORDER BY DateTime DESC";
try
{
logQuery.ExecuteBatch(szQuery, parse, output);
}
catch
{
};
}
}
}

Use Execute instead of ExecuteBatch:
MSUtil.ILogRecordset RecordSet = logQuery.Execute(query, oInputFormat)
If you want to export to CSV in your sample code you need to change the query by adding INTO output_file_name and run ExecuteBatch:
string szQuery = "SELECT Folder, User, Record, DB, TO_LOCALTIME(Timestamp) AS DateTime, Operation, Checked **INTO c:\out\out.csv** FROM " + szFileName + " ORDER BY DateTime DESC";

Related

c# Upload File to SharePoint Document Library

My requirement is the following:
I have various bits of network hardware, from which we regularly export configurations (this is done using another c#/.NET app I created, this works really well - the tool logs in via SSH to the various devices and downloads the latest configuration to the local hard disk of the server from which the app runs).
We have various SharePoint online sites (provided via our M365 subscription).
I want to have these configs uploaded to a particular folder, in a particular document library, in a particular SharePoint Online site, basically so that there is an off-site backup of the config files.
I was following the steps in this blog: https://daoudisamir.com/from-c-to-sharepoint-file-upload-using-csom-with-subfolders-structure/.
It looked like it did what I wanted... but when I try to build the code, it tells me that I'm missing references to assemblies etc. I know that this means that I'm missing "using" directives, but I've tried all sorts of variations to reference the various NUGET packages that are instructed to be installed, but I can't get this to work and couldn't see anywhere on the blog itself to email the owner.
Anyone got any ideas... at the moment, my code is more or less a copy/paste of what's on the blog page, but I've included my code here for convenience:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Security;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
namespace UploadToSharePoint_Net48
{
internal class Program
{
static void Main(string[] args)
{
string SiteUrl = "https://You.sharepoint.com/sites/Upload";
string DocumentLibrary = "UploadLibrary";
string FileName = #"C:\testupload.pdf";
string CustomerFolder = "1564_dsfgsst";
string UserName = "samir.daoudi#******.co.uk";
string Password = "*****";
UploadFileToSharePoint(SiteUrl, DocumentLibrary, CustomerFolder, FileName, UserName, Password);
}
private static void UploadFileToSharePoint(string SiteUrl, string DocLibrary, string ClientSubFolder, string FileName, string Login, string Password)
{
try
{
#region ConnectToSharePoint
var securePassword = new SecureString();
foreach (char c in Password)
{ securePassword.AppendChar(c); }
var onlineCredentials = new SP.SharePointOnlineCredentials(Login, securePassword);
#endregion
#region Insert the data
using (SP.ClientContext CContext = new SP.ClientContext(SiteUrl))
{
CContext.Credentials = onlineCredentials;
SP.Web web = CContext.Web;
SP.FileCreationInformation newFile = new SP.FileCreationInformation();
byte[] FileContent = System.IO.File.ReadAllBytes(FileName);
newFile.ContentStream = new MemoryStream(FileContent);
newFile.Url = Path.GetFileName(FileName);
SP.List DocumentLibrary = web.Lists.GetByTitle(DocLibrary);
//SP.Folder folder = DocumentLibrary.RootFolder.Folders.GetByUrl(ClientSubFolder);
SP.Folder Clientfolder = DocumentLibrary.RootFolder.Folders.Add(ClientSubFolder);
Clientfolder.Update();
SP.File uploadFile = Clientfolder.Files.Add(newFile);
CContext.Load(DocumentLibrary);
CContext.Load(uploadFile);
CContext.ExecuteQuery();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("The File has been uploaded" + Environment.NewLine + "FileUrl -->" + SiteUrl + "/" + DocLibrary + "/" + ClientSubFolder + "/" + Path.GetFileName(FileName));
}
#endregion
}
catch (Exception exp)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(exp.Message + Environment.NewLine + exp.StackTrace);
}
finally
{
Console.ReadLine();
}
}
}
}
The errors are with all the references to SP.xxxxx
I can see that there is no definition for anything called "SP", but I'm assuming at this stage that this is in one of the external libraries or whatever is in the NUGETS that are required.
Any help gratefully received.
Thanks
Colin

Revit IExternal Application Error- doesn't seems to run at all

Should we have something with the External application to properly register the event?
I also tried putting two breakpoints one inside the start module and other inside the Export module.
the first responded and waited for me to continue and the next didn't respond(hope did not run the line)
Also,I had manually tried coping the addin file to the addin location to avoid any post build event error but still doesnt seem to work.
could you tell me what I am I doing wrong here.
Here is the code :
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.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.UI.Events;
using Autodesk.Revit.DB.Events;
using System.IO;
namespace UserDataSheet
{
[Transaction(TransactionMode.Manual)]
[Regeneration(RegenerationOption.Manual)]
public class UserDataSheetclass : IExternalApplication
{
public Result OnShutdown(UIControlledApplication application)
{
return Result.Succeeded;
}
public Result OnStartup(UIControlledApplication application)
{
try
{
// Register event.
application.ControlledApplication.DocumentOpened += new EventHandler<Autodesk.Revit.DB.Events.DocumentOpenedEventArgs>(ExportLog);
return Result.Succeeded;
}
catch (Exception)
{
return Result.Failed;
}
}
public void ExportLog(object sender, DocumentOpenedEventArgs args)
{
var doc = sender as Document;
var isFamilyDoc = doc.IsFamilyDocument;
// variables to use
string RevitUserName = "";
DateTime OpenTime = new DateTime();
string localUserName = "";
string filename = "";
string filepath = "";
string content = "";
if (isFamilyDoc == false)
{
var IsloggedIn = Autodesk.Revit.ApplicationServices.Application.IsLoggedIn;
if (IsloggedIn == true )//&& doc.IsModelInCloud == true)
{
// use variables
filepath = doc.PathName;
filename = doc.Title;
RevitUserName = doc.Application.Username;
OpenTime = DateTime.Now;
localUserName = System.Environment.MachineName;
}
content = string.Format("Date and time : {0} \n Revit UserName : {1} \n Local PC UserName : {2} \n FileName : {3} \n FilePath : {4} "
, OpenTime.ToString(), RevitUserName, localUserName, filename, filepath);
TaskDialog.Show("Model Open Writer info", "user and file details : \n " + content);
}
var writefilepath = Path.GetTempPath();
var Writefile = writefilepath + "//records.txt";
FileStream fs = new FileStream(Writefile, FileMode.Append);
StreamWriter writer = new StreamWriter(fs);
writer.Write(content);
writer.Close();
File.OpenRead(Writefile);
}
}
}
First of all, you can completely remove the TransactionMode and RegenerationOption. The latter is completely obsolete and does nothing at all anywhere whatsoever. The former is only useful when declaring an external command. It is useless and ignored in the context of an external application.
Secondly, to address your question: you can set a breakpoint in the beginning of OnStartup. If the breakpoint is not hit, your add-in is not being loaded at all. Probably something is wrong with your add-in registration, e.g., in the add-in manifest *.addin file.
Go back to square one, i.e., work through the getting started material and the developer guide instructions on registering and loading a Revit add-in.
If the breakpoint in OnStartup is hit, then your add-in is loading correctly, which means that the add-in manifest *addin file is OK. So, you do not need to worry about that. The VisibilityMode tag is not used for external applications, by the way.
Thanks, Jeremy It worked
Firstly I apologies for adding this as answer( I don't know how to add codes in comment)
It worked when I deleted my Addin file and recreated it may be I had made some mistake in it.
meanwhile I have copied the following code from examples and used it,honestly I did't understand this line of the code.
"public void ExportLog(object sender, DocumentOpenedEventArgs args)"
can you point to a right source that explains this part. I have three questions here :
what object type is sender and args are they of type application?
How do I add a 3rd parameter to this method say I want the user to input a string to name the file the data is copied to.
Can I do this
var newEvent = new EventHandler<Autodesk.Revit.DB.Events.DocumentOpenedEventArgs>(ExportLog);
instead of
application.ControlledApplication.DocumentOpened += new EventHandler<Autodesk.Revit.DB.Events.DocumentOpenedEventArgs>(ExportLog);
why does all example use += is this to register the event every time a new instance of Revit is opened?
Thanks for your help.
You can see the class of sender yourself by setting a breakpoint at the beginning of ExportLog and looking in the debugger.
No, you cannot modify the signature of the event handler. It is predetermined by the Revit API.
Yes.
It sounds to me as if you might save some time and effort for yourself by learning a bit more about the basics of C# and .NET programming in general before continuing to tackle this task.

Problems to Get Data using Tesers on nHapi hl7

Hello again dear community, i am using " Tersers " to get data from an hl7 v2 messeage, its a ADT_A08 messeage.
Well the thing is that, im trying to get the PatientName with this: string test = terser.Get("PID-5-1"); and that return me nothing, instead if i use the same but changing the command for something like "MSH-16-2" i dont remember, but its work, why it still happend me that? i need to use things like PID-5-2 or EVN-2 , that commands does not work at all. The same happens when I use "MSH-152-2"; the return is the name of a medication, but that is typical of one of my hl7-v2 messages, but I would have to use "RXE-2-1" to get the same data. I apologize for my english , im spanish-language native.
using NHapi.Base.Model;
using NHapi.Base.Util;
using NHapi.Base.Parser;
using System.Diagnostics;
using NHapi.Model.V23.Message;
using System.IO;
public void someMethod()
{
string msg = txtHL7m.Text;
PipeParser pParser = new PipeParser();
var iMesseage = pParser.Parse(msg, "2.3");
try
{
var terser = new Terser(iMesseage);
string test = terser.Get(txtTerserExpression.Text);
txtTerserResults.Text = test;
}
catch
{
Console.WriteLine("ERROR");
}
}
//I expect the patientsData using the correct sintaxis of tesers

CRM Plugin will not update or do anything to change a fields value

So I have written a plugin to do some simple calculations and and update fields based upon certain conditions. The plugin compiles and doesn't cause any errors while profiling or create any instances where I can debug my code which is frustrating. Anyways without further ado here it is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BPT.PluginCommon.BaseClasses;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Xrm;
namespace Engage.Crm.Plugins
{
public class VoidPayment : BPTPluginBase
{
bpt_DuesHeader oDuesHeader = new bpt_DuesHeader();
Account org = new Account();
public override void HandleAfterOp()
{
try
{
base.HandleAfterOp();
var crmContext = new XrmServiceContext(this.OrganizationService);
if (this.PluginExecutionContext.MessageName == MessageName.Create ||
this.PluginExecutionContext.MessageName == MessageName.Update)
{
if (this.InputTargetEntity.Attributes.Contains("gih_void"))
{
var Void = (bool) this.InputTargetEntity.Attributes["gih_void"];
var voidReason = (OptionSetValue) this.InputTargetEntity.Attributes["gih_voidreason"];
var totalPayments = (Money) this.InputTargetEntity.Attributes["bpt_TotalPayments"];
var amountBilled =
crmContext.bpt_DuesHeaderSet.Where(
o => o.bpt_DuesHeaderId == this.PluginExecutionContext.PrimaryEntityId)
.ToList()
.Sum(o => o.bpt_TotalAmountBilled == null ? 0 : o.bpt_TotalAmountBilled.Value);
if (Void)
{
this.oDuesHeader.bpt_TotalAdjustments = new Money(amountBilled);
this.oDuesHeader.bpt_TotalAmountBilled =
new Money(oDuesHeader.bpt_TotalAdjustments.Value + totalPayments.Value);
this.oDuesHeader.bpt_Balance = new Money(amountBilled);
if (voidReason.Value == 914020000)
//should be dropped not default option
{
oDuesHeader.gih_terminationdate = DateTime.Now;
}
}
OrganizationService.Update(oDuesHeader);
}
}
}
catch (Exception ex)
{
this.TracingService.Trace(this.ToString() + " {0}", "Exception: {0}", ex.ToString());
throw;
}
}
}
}
Sorry code is not formating well! Help! The plugin is registered as post-operation and synchronous. Any insight would be helpful and if a moderator could help format the code that would be greatly appreciated because it is not letting me add four spaces in certain places.
Plugins in CRM are created once, and then used multiple time, maybe even simultaneously, so besides setting the Id, don't use class level fields. You're creating a race condition that could really do some unwanted changes.

Skype issue with multiple params

I am trying to make a C# Stress script but it keeps giving me the error: Error Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement.
Code:
using System;
using System.Collections.Generic;
using System.Text;
using Skyper;
using SKYPE4COMLib;
using System.Net;
namespace Skyper.plugins
{
public static class Help
{
public static string Description
{
get
{
return "Stresser";
}
}
public static void Execute(string[] Params, int chat, string username)
{
Skyper.SendMessage(chat, Params[1] + "" + new WebClient().DownloadString("http://example.com/stresser/api.php?key=examplekey&host=" + Params[1]));"&port=&time=&method=";
}
}
}
How this script will work is users in Skype will type in !stress ip, port, time, method and then it will submit it to the API.
Following is a simple string, which is not assigned to any thing,
"&port=&time=&method=";
So may be you can use something like:
Skyper.SendMessage(chat, Params[1] + "" + new WebClient().DownloadString("http://example.com/stresser/api.php?key=examplekey&host=&port=&time=&method=" + Params[1])");
or change that string properly with double quotes and brackets end symbols

Categories

Resources