HI,
I'm new to Windows form app and trying to build one prototype app. I've designed a data entry form and coded the business logic. Now, I'm trying to open the data entry form from my welcome form. But every time I run "Welcome" form, my data entry form runs ( it's created before welcome form ) . Where can I set the form's order of execution ?
Here is the form1 code,
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
namespace PrototypeApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
string pdfTemplate = "C:\\app\\End_Of_Project_Client_Evaluation_Template.pdf";
string newFile = "C:\\app\\End_Of_Project_Client_Evaluation_Template_update.pdf";
PdfReader reader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create));
AcroFields fields = pdfStamper.AcroFields;
fields.SetField("client", txtClient.Text);
fields.SetField("project", txtProject.Text);
fields.SetField("project_area", txtArea.Text);
fields.SetField("project_no", txtLandProjectNo.Text);
fields.SetField("suggestions", txtSuggestions.Text);
fields.SetField("project_strength", txtStrengths.Text);
fields.SetField("other_suggestions", txtComments.Text);
pdfStamper.FormFlattening = false;
// close the pdf
pdfStamper.Close();
MessageBox.Show("Pdf document successfully updated!!");
}
}
}
In your solution you have a file called Program.cs, open it and change the following line:
Application.Run(new Form1());
to
Application.Run(new WelcomeForm());
where WelcomeForm is the name of your welcome UI class. This change will make you welcome form to show up when you start the application, after that you can add some code to start the other form when you want.
Related
I am in need of help.
I have created a dockable WPF within Revit.
It is working well and I can 'show' & ;hide' from push buttons.
My aim is to create buttons within the WPF that run custom commands.I dont need to interact or show any information within the WPF, its purely just acting as a push button but in the WPF instead of a ribbon.
The commands currently work and can be executed via the Add-In Manager.
Below is the command I am trying to run:
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using System.Collections.Generic;
using System.Linq;
namespace Adams.Commands
{
[Transaction(TransactionMode.Manual)]
[Regeneration(RegenerationOption.Manual)]
public class PrecastDisallowJoin : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
var uiApplication = commandData.Application;
var application = uiApplication.Application;
var uiDocument = uiApplication.ActiveUIDocument;
var document = uiDocument.Document;
// Prompt the user to select some walls
var references = uiDocument.Selection
.PickObjects(
ObjectType.Element,
new WallSelectionFilter(),
"Please select walls");
var components = references.Select(r => document.GetElement(r)).ToList();
// Start a transaction
using (Transaction t = new Transaction(document, "Change Wall Join Behavior"))
{
t.Start();
// Loop through the selected walls and change their join behavior
foreach (Reference reference in references)
{
Wall wall = document.GetElement(reference) as Wall;
WallUtils.DisallowWallJoinAtEnd(wall, 0);
WallUtils.DisallowWallJoinAtEnd(wall, 1);
}
// Commit the transaction
t.Commit();
}
return Result.Succeeded;
}
public class WallSelectionFilter : ISelectionFilter
{
public bool AllowElement(Element elem)
{
//return elem is FamilyInstance;
return elem.Name.Contains("Precast");
}
public bool AllowReference(Reference reference, XYZ position)
{
return true;
}
}
}
}
My XAML.cs looks like this:
using Autodesk.Revit.UI;
using System.Windows.Controls;
using Adams.Commands;
using System.Windows;
namespace Adams.ui
{
public partial class Customers : UserControl
{
public UIDocument uIDocument { get; }
public ExternalCommandData commandData { get; }
public Customers(UIDocument uIDocument )
{
InitializeComponent();
}
private void btnStartExcelElementsApp_Click(object sender, RoutedEventArgs e)
{
string message = string.Empty;
PrecastDisallowJoin precastDisallow = new PrecastDisallowJoin();
precastDisallow.Execute(commandData, ref message, null);
}
}
}
Any ideas of what i should be trying?
I'm new to creating add-ins and appreciate any help offered.
If I have missed any critical info please let me know.
Thank you all
When I tried the above it crashes Revit.
Im not sure how to pass the required information in the Execute method in the XAML.
The Revit dockable dialogue and hence your WPF form lives in a modeless context. It does not execute within a valid Revit API context. A valid Revit API context is only provided by Revit itself, within the event handlers called by Revit when specific events are raised. For instance, clicking a button to launch an add-in external command raises the IExternalCommand.Execute event.
The Building Coder shares a long list of articles on Idling and External Events for Modeless Access and Driving Revit from Outside
explaining how to gain access to a valid Revit API context from a modeless state.
You can address your task by using an external event:
Idling Enhancements and External Events
External Command Lister and Adding Ribbon Commands
External Event and 10 Year Forum Anniversary
Implementing the TrackChangesCloud External Event
Vipassana and Idling versus External Events
The question has also been discussed many times in the Revit API discussion forum, so you can check there for threads including WPF, dockable and external event.
You can use IExternalEventHandler:
public class MyExternalEvent : IExternalEventHandler
{
public void Execute(UIApplication app)
{
//do your revit related stuff here
}
public string GetName()
{
return "xxx";
}
}
Create external event:
ExternalEvent myExEvent= ExternalEvent.Create(new MyExternalEvent());
In order to effectively use the above you will have to hold reference to "myExEvent" in some ViewModelClass then you will be able to raise this event inside your xaml.cs:
ViewModelClass.TheEvent = myExEvent;
ViewModelClass.TheEvent.Raise();
EDIT: What you were trying to do is unfortunately not acceptable with revit API. WPF window displayed as dockpanel does not have access to valid revit api context. IExternalEventHandler gives you the possibility to somehow link dockpanel user interface with revit api.
I'm trying to build a service to export a rdlc Localreport from one of my actions in my webapi. Webapi is built on .net core 3.1
I know that reportviewer is not compatible with .net core, so to try and mitigate that I've got a class library project added to my project based on .net framework 4.7.2. Added the reference to the class library to my .net core webapi, so far so good. I'm able to call methods from my class library, no problem.
Now try adding LocalReport to a class in my class library....
using Microsoft.Reporting.WebForms;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Reports
{
public class RenderAction
{
public void GetOrderReport()
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
string p = Path.GetDirectoryName(path);
string reportPath = Path.Combine(p, "Reports","Order.rdlc");
if (!File.Exists(reportPath)) { return; }
var report = new LocalReport();
}
}
}
intellisense prompted to install Microsoft.Reporting.Viewer so I did so... When calling my function in runtime, I get the following error when creating the new instance of localreport:
System.MissingMethodException
HResult=0x80131513
Message=Method not found: 'Void System.AppDomainSetup.set_ActivationArguments(System.Runtime.Hosting.ActivationArguments)'.
Source=Microsoft.ReportViewer.Common
StackTrace:
at Microsoft.Reporting.ReportRuntimeSetupHandler.InitAppDomainPool(Evidence sandboxEvidence, PolicyManager policyManager)
at Microsoft.Reporting.LocalService..ctor(ILocalCatalog catalog, Evidence sandboxEvidence, PolicyManager policyManager)
at Microsoft.Reporting.ControlService..ctor(ILocalCatalog catalog)
at Microsoft.Reporting.WebForms.LocalReport..ctor()
at Myproject.Reports.RenderAction.GetOrderReport() in C:\Users\RudiGroenewald\source\repos\Myproject-Api-Common\Myproject_Api_Common\Myproject_Reports\RenderAction.cs:line 24
at Myproject.Api.Common.Controllers.ReportsController.Get() in C:\Users\RudiGroenewald\Source\Repos\Myproject-Api-Common\Myproject_Api_Common\Myproject_Api_Common\Controllers\ReportsController.cs:line 22
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<<InvokeActionMethodAsync>g__Logged|12_1>d.MoveNext()
It seems like some sort of dll version mismatch or something... a bit stumped really.
Is it just not possible to get this working? My alternative is to have a full .net webapi, just for reportwriting, which I prefer not to do. Any thoughts on what I'm doing wrong?
I followed this tutorial to combine a few DLL's into my EXE.
http://www.digitallycreated.net/Blog/61/combining-multiple-assemblies-into-a-single-exe-for-a-wpf-application
The way I understand this works is:
- it starts by telling the compiler to embed (as embedded resources) each and every DLL that have their Local Copy set to True.
That part is working fine. It apparently doesn't "add" them as resources to my project (figure 1 in the tutorial kind of says otherwise), but I can tell that the size of my EXE is correct.
FYI, my program uses WPFtoolkit, in my case, that's 2 DLL's:
system.windows.controls.datavisualization.toolkit.dll
WPFToolkit.dll
Then, I set the Build Action of my App.xaml to Page, and made a program.cs file which I added to my project.
this is my project.cs:
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
using System.IO;
using System.Reflection;
using System.Globalization;
namespace Swf_perium {
public class Program {
//[System.Diagnostics.DebuggerNonUserCodeAttribute()]
//[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[STAThreadAttribute]
public static void Main() {
Swft_perium.App app = new Swf_perium.App();
AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
app.InitializeComponent();
app.Run();
}
private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args)
{
Assembly executingAssembly = Assembly.GetExecutingAssembly();
AssemblyName assemblyName = new AssemblyName(args.Name);
string path = assemblyName.Name + ".dll";
Console.WriteLine(path);
if (assemblyName.CultureInfo.Equals(CultureInfo.InvariantCulture) == false)
{
path = String.Format(#"{0}\{1}", assemblyName.CultureInfo, path);
}
using (Stream stream = executingAssembly.GetManifestResourceStream(path))
{
if (stream == null)
return null;
byte[] assemblyRawBytes = new byte[stream.Length];
stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length);
return Assembly.Load(assemblyRawBytes);
}
}
}
}
After I build the project, I run it off VS2013, no problem, since both DLL's have their local copy set to true. If I go in my debug folder, take both DLL's out and run the EXE off windows explorer, then the program instantly crashes because it can find the DLL's.
What this tutorial should allow me to do is being able to run that EXE by itself without the DLL's, so yeah, it doesn't work.
I added a console writeline of the path that are being read by the OnResolveAssembly method of my program.cs. And here's what I get:
4 times the same path:
"Swf_perium.resources.dll"
Obviously, when it gets to the Stream, it's null and the method then returns null.
I am trying to understand where these paths are coming from? I don't understand why 4? And why this path?
Has anyone ever tried this technique? Comments on the blog show pretty good success rate.
Does anyone have an idea?
I made several mistakes to get to this stage, but at this point I don't see what I am doing wrong.
Thanks
Steve
EDIT: following HB's guidance, here's what I did:
I took the MSBuild target "mod" out.
Set both references' copy local to FALSE.
Added both DLL as embedded resources manually. They're both into the "Resources" directory at the root of the project.
I set App.xaml build action back to "ApplicationDefinition".
And I excluded my program.cs out of the project.
and added this code to App.xaml.cs:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Reflection;
namespace Swf_perium
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
public App()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
var execAssembly = Assembly.GetExecutingAssembly();
string resourceName = execAssembly.FullName.Split(',').First() + ".Resources." + new AssemblyName(args.Name).Name + ".dll";
Console.WriteLine(resourceName);
using (var stream = execAssembly.GetManifestResourceStream(resourceName))
{
byte[] assemblyData = new byte[stream.Length];
stream.Read(assemblyData, 0, assemblyData.Length);
return Assembly.Load(assemblyData);
}
}
}
}
now, the console prints out of the 2 DLL's filename, but not the other.. I am guessing that's why it's still not working..
that's where I'm at.
edit:
The DLL that doesn't show is not called by my code directly. it's a dependence from the first DLL. I took that second DLL out of references and resources.. If I set copy local to true for the first DLL (which my program actually uses), building the project generates both DLL at the root - in this case with both dlls generated the program works, funny thing is if I delete that second DLL, the program still works. So the problem isn't that second DLL but the first one.
the error I have (which I've had all along no matter what technique I use) is that my XAML is calling that namespace and can't find it!
edit:
Ok, well it still doesn't work. I've brought my program.cs back into the solution, set it as the entry point. And added the code suggested by HB into it.
I made sure that the assemblyresolve is done on the first line of the main so that's it's done before any wpf is done. I even added a 5s sleep just to make sure that the dll was loaded before any wpf happens. Still no go.
Either the dependence to the second DLL is what's causing a problem (?) or maybe the way I import the namespace in my XAML is incorrect. Do I need to specify that this namespace is embedded? and where it's located - i.e. its path?.
thanks
Perhaps look at Costura where it will do all the hard work of embedding assemblies for you.
Don't know your project structure but i usually add a directory for the assemblies to the root of the project and then add the dlls to that directory as embedded resource. I also then turn off the local copy of the references to make sure that it works.
Here is the code i use in my App.xaml.cs:
static App()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
var execAssembly = Assembly.GetExecutingAssembly();
string resourceName = execAssembly.FullName.Split(',').First() + ".ReferencedAssemblies." +
new AssemblyName(args.Name).Name + ".dll";
using (var stream = execAssembly.GetManifestResourceStream(resourceName))
{
byte[] assemblyData = new byte[stream.Length];
stream.Read(assemblyData, 0, assemblyData.Length);
return Assembly.Load(assemblyData);
}
}
Simply replace the ".ReferencedAssemblies." string according to the directory you placed the dlls in.
(Using the static constructor of the class makes sure that the event is hooked up before any code that potentially accesses referenced assemblies is executed, in your code i would move the hook to the first line of Main, that may already solve your problem.)
I do not have much experiece of WPF, and I consider it as an easier way to markup/coding UI in .net.
I have install the lastest Rx release, and play it using Console application without any issue, when I used it in a simple WPF application, it seems that 'Observable' is not liked by WPF...
I have added both reference to:
System.CoreEx
System.Reactive
when type in the button click's event handler, the VS intelligent happily pickup the Observable class and its static members, however when compile it, the 'Observable' becomes unknown to the context. Also the intelligence is gone for the class...
If I remove the above two reference, and add them back in again, the intelligence picked it up... when compile, same situation happens again...
I also installed the silverlight version of rx, not still not luck, please advice and help.
private void btnStart_Click(object sender, RoutedEventArgs e)
{
CheckBox[] chbServers = new CheckBox[] { chbMx1, chbMx2, chbMx3, chbMx4 };
ListBox[] lbxFiles = new ListBox[] { listBox1, listBox2, listBox3, listBox4 };
for (int i = 0; i < chbServers.Length; ++i)
{
if (chbServers[i].IsChecked == true)
{
string baseDir = string.Format(#"c:\maildrop\mx{0}", i + 1);
if (Directory.Exists(baseDir))
{
DirectoryInfo di = new DirectoryInfo(baseDir);
FileInfo[] fis = di.GetFiles("*.eml", SearchOption.AllDirectories);
//Observable.GenerateWithTime(
// 0,
// index => index <= fis.Length,
// index => index + 1,
// index => fis[index].Name,
// _ => TimeSpan.FromMilliseconds(300)
// )
// .ObserveOnDispatcher()
// .Subscribe(name =>
// {
// // delete the file
// lbxFiles[i].Items.Remove(name);
// });
}
}
}
}
The commented code is the piece which cause problem...
using System;
using System.Collections.Generic;
using System.Disposables;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
all namespace refereced are as above...
WPF applications use the .NET 4 Client Profile by default, which was not supported by Rx until the latest release. Changing your project settings to use the full .NET 4 framework will allow you to compile.
How does a Silverlight application ask the browser what domain its being served up from?
UPDATE:
Make sure if your class doesn't already have this using statement add it at the top your class. This will help you on some of the examples you'll see online. It confused me for a bit.
using System.Windows.Browser;
How about HtmlDocument.DocumentUri? That'd get you what you need. Page about browser interop here.
As jcollum says you access the HtmlDocument.DocumentUri property to get lots of information on the host. To answer the question in your comment this is how you do this in Page.xaml.cs:
using System;
using System.Windows.Browser;
using System.Windows.Controls;
namespace SilverlightApplication1
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
string hostName = HtmlPage.Document.DocumentUri.Host;
int port = HtmlPage.Document.DocumentUri.Port;
}
}
}