Auto Include a class in a C# file being served from IIS - c#

I am making a simple api without any ide. I have three files in my website's root.
default.aspx
<%# Page Language="C#" src="default.cs" inherits="foo" %>
default.cs
using System;
using System.Web;
using System.Web.UI;
using TechStreet;
using MySql.Data.MySqlClient;
public class foo : Page {
protected void Page_Load(object sender, EventArgs e) {
Response.Write(Database.Query("SELECT * FROM users", new String[0]));
}
}
Database.class.cs
namespace TechStreet {
public class Database {
public static string Query(string query, string[] parameters) {
return "done";
}
}
}
My problem is that loading default.aspx, it rightfully doesn't recognize the TechStreet namespace because I never tell them where the file is. If I understand this correctly then I need to compile both these files together or provide a reference to the database.dll when I compile default.cs. But I never compile default.cs. It gets compiled automatically when the page is first loaded.
Another solution is to compile the database.cs and put it in /bin/. But I will have to do this every time I make a change in the file.
So my question is, is there any way to "tell" default.cs to also auto compile and reference the database.cs when it compiles itself?

Move the Database.class.cs into the App_Code directory.

Related

Load Assembly at Runtime .NET 6

We are in the beginning stages of converting a c# Winforms App from .NET Framework to .NET 6. We can get the project to build and run in .NET 6, but when it comes to a dynamically loaded assembly, we are having issues. We can get the assembly to load but attempting to access the custom class within it returns a null. I recreated this scenario in two smaller projects as an example.
Solution 1/Project 1 - The code for the assembly to be loaded into the main application. This is a class library that creates the TestAssembly.dll
namespace Custom.TestAssembly
{
public class TestClass : CallingModule
{
public override object GetValue()
{
return "Hello World";
}
}
}
Solution 2/Project 1 - This is a project and class within the main application's solution. This is a class library that creates the Custom.TestAssembly.dll
namespace Custom.TestAssembly
{
public class CallingModule
{
public virtual object? GetValue()
{
return null;
}
}
}
Solution 2/Project 2 - A button has been placed on a form. When it is clicked, the assembly should be loaded, which it is. However, attempting to extract the class from the assembly always returns a NULL.
Form1.cs
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Loader;
namespace TestCallingApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Assembly dynamicAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(#"C:\LocationOf\TestAssembly.dll");
Module customizationModule = dynamicAssembly.GetModule("TestAssembly.dll");
Type customClientModule = customizationModule.GetType("Custom.TestAssembly.TestClass"); //THIS RETURNS A NULL??
}
}
}
Just trying to understand what I am missing. Any thoughts? Or a better way to load runtime assemblies and access classes within them in .NET 6?
Did you reference Solution 2/Project 1 ?
Since they have the same assembly name Custom.TestAssembly, the runtime will not load it again if already loaded in memory.
You can, however, load it under a different AssemblyLoadContext, there's an example on MSDN as well.
Also, you may want to take a look at DotNetCorePlugins, which takes care of assembly loading, reloading, isolation, shared type, and dependency resolving.

Visual studio forms : Add local index.html file in visual studio webbrowser

I am working on a visual studio project in which I have a webpage I would like to display in webbrowser. Currently I have a folder named resources in which I have copied all the required html,js and css files, but I don't know how to point it in the project. Any ideas? Thank you.
Code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
string appPath = Assembly.GetEntryAssembly().Location;
string filename = Path.Combine(Path.GetDirectoryName(appPath), "resources\\index.html");
notes.Navigate(filename);
}
}
}
Thank you.
Update
I have pasted the contents of the resources folder directly in the project, and tried multiple options suggested in the URL. Unfortunately, nothing is working, and I am new to Visual studio, so don't even have an idea what's going wrong. Updated code :
private void Form1_Load(object sender, EventArgs e)
{
//string curDir = Directory.GetCurrentDirectory();
//this.notes.Url = new Uri(String.Format("file:///resources/index.html", curDir));
string applicationDirectory = Path.GetDirectoryName(Application.ExecutablePath);
string myFile = Path.Combine(applicationDirectory, "index.html");
notes.Url = new Uri("file:///" + myFile);
}
If you want to open a link in a browser from your desktop app (e.g. "show in the browser" button in WinForms app), you can use System.Diagnostics.Process.Start("http://localhost:42") as it's discussed here (production code will have some non-localhost link there).
Before that you should host your website on local IIS and specify the port (e.g. 42) there.
On the other hand, if you want to create a web application (with C# back-end code), you should use another type of project (not WinForms), e.g. ASP.NET MVC
EDIT:
System.Diagnostics.Process.Start also works with local files, e.g. System.Diagnostics.Process.Start(#"C:\Sites\index.html");
EDIT 2:
You also could use application directory e.g. System.Diagnostics.Process.Start(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"site\index.html")) to keep paths in your app relative

In Visual Studio C# project do files aware the other file content without putting a using statement?

Say If we use two separate files called a.cs and b.cs in a C# project using VISUAL STUDIO, my question is does one file aware of the other WITHOUT putting a using statement about the other file. ie In the file a.cs can we use a class that is already defined in b.cs but not putting a using b.cs; statement in the beginning of the file?.When we compile altogether will the project know each file content and won't raise any error?
I guess you are on the wrong track here. Files don't interact with each other. But the classes do. Namespaces are used to refer to the class that are meant to be used. You can change the file name to anything several times, it won't affect your project. Moreover you can put many classes inside the same file name under the same namespace and you won't have to use using.
Just consider this scenario, Namespace are the area code, and the phone numbers are the classes. Being in the same area already, you don't have to use the area code to call a different number that exists in the same area. But if you are dialling a number outside your area, you would want to use the area code. Basically by adding area code(namespace) infront of the number, you are applying using to refer to the other number(class). Hope you got the idea.
Edit: Explaining programmatically
Suppose this is your Area
using something;
using someotherthing;
namespace MyMainNamespace
{
private class MyMainClass
{
private void blahblah { ... }
}
private class ClassABC
{
private void blahblah { ... }
}
private class ClassXYZ
{
private void blahblah { ... }
}
}
See, in the above example, to interact with the MyMainClass, ClassABC & ClassXYZ. you don't have to use using MyMainNamespace;. Because they all lie in the same area MyMainNamespace. But there exists a class in another namespace like shown below:
using something;
using someotherthing;
namespace SubNamespace
{
public class SecondaryClass
{
public void apple{ ... }
}
}
If you want to access SecondaryClass which lies in SubNamespace(different area) you would have to use using SubNamespace; in your main area. Like:
using something;
using someotherthing;
using SubNamespace; //add the namespace
namespace MyMainNamespace
{
private class MyMainClass
{
private void blahblah {
...
// Now you can use methods & functions that exist in `SecondaryClass`
SecondaryClass secondary = new SecondaryClass();
secondary.apple();
....
....
}
}
}
Hope this is enough to get the idea by now
Also, it doesn't matter that these namespace(MyMainNamespace & SubNamespace) lies in the same file or different file. You NEVER REFER TO THE FILENAME(filename.cs) by applying using. You ALWAYS REFER TO THE NAMESPACES.
If the C# code in a.cs and b.cs are inside the same namespace, then no using statement should be needed. If the 2 cs files use different namespaces, then you will have to put a using statement for the namespace of the code you want to reference.

default webform using and namespace queries

When creating webform in VS 2013, the codebehind contains several using alias but when I save the page all the using alias are removed. Only one using using System; is kept. Why is it so?
Also the code behind has namespace, when I see different web pages tutorials they simply start with public partial class. What is the difference ? Should I simply remove the namespace, does it effect my webpages ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Sample.UI.pages
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
1) If you aren't adding any extra code that would be accessible via a using statement, then you don't need any extra using statements.
2) public partial class refers to the fact that the class is split over 3 files. One is the aspx file, the designer.cs file, and the aspx.cs code behind. Do not remove any namespaces unless you know what you're doing. The CLR uses the assemblies namespaces to find code to execute.

How do I access a public page variable of the only page from the master page?

I have a page - only ONE page for the entire site:
using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class CMSPageViewer : System.Web.UI.Page
{
public int myPageID;
protected void Page_PreInit(object sender, EventArgs e)
{
// Get stuff from the database
myPageID = 1;
// Set the Page.MasterPageFile
}
protected void Page_Load(object sender, EventArgs e)
{
// Fill in the page contents
// This looks for and fills in asp:ContentPlaceHolder controls based on ID
}
}
And the master page:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Standard_Page : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
int myID = (this.Page as CMSPageViewer).myPageID;
}
}
How can I access ID from the MasterPage that is used?
Casting the page doesn't seem to work. I get the following error:
Compiler Error Message: CS0246: The type or namespace name 'CMSPageViewer' could not be found (are you missing a using directive or an assembly reference?)
Define a variable in your master page. Give it proper getter/setters. In each page call the master.setter and "pass the variable into" the master page.
At the very least you're going about it wrong, but this is what you have to do.
Referencing "ASP.NET 3.5 Unleashed" http://www.amazon.com/dp/0672330113 section in Chapter 5 pages 255 - 260 for modifying Master properties based on the Page being interpreted.
Again, Referencing ASP.NET 3.5 Unleashed Chapter 6 which starts off:
Themes are different than Master Pages. A Master Page enables you to share content across multiple pages in a website. A Theme, on the other hand, enables you to control the appearance of the content.
So in other words, you're not supposed to use a Master Page as a Theme, the two work together.
Do you want me to keep going? I've got a few other books. I've done exactly what you're trying to do (modify the master based on the content) and at the time I knew it was a hack, but I did it because I had to. So what I'm telling you is what I did, which is what works.
Now please, again, tell me that what I'm suggesting can't be done. I'll go find some more references that will explain why you can't cast to a Page from within the Master.
For those looking to lay the smack down on my turning to a book for reference, note that that's how the big boys play, it's how the people who get the actual contracts play, and it's how you inform your boss. It's a book. That's what they're for. Additionally, Stephen Walther is not a nobody, he was a Senior Product Manager for the ASP.NET team. So he knows what the hell he's talking about. I would listen to his advice. Hell, I bought his book didn't I?
I dislike the design, but if there is only a single page in the application, then this begins to make more sense.
In fact, this is not what master pages are for. This is what themes are for.
In your master page use this:
(this.Page as CMSPageViewer ).ID
Couldn't you use a session variable that you could access from both the page and the master page.
HttpContext.Current.Session[key] = value;

Categories