Using QueryString to include pages - c#

I program in PHP and am trying to learn C#, but I'm having some difficulties.
In PHP, I have a function include_once() to include other pages using the global $_GET.
I use this code in PHP with QueryString (i.e.: ?param=add):
if($_GET['param'] == 'add') {
include_once('pages/caseAdd.php');
} else {
include_once('pages/caseDefault.php');
}
I wonder how do I make such a process in Visual Studio using C# (ASP.NET).

Instead of PHP, C# compiles the code and you can't do exactly the same thing. Howewer you can create custom user controls (.ascx files), i.e. caseAdd.ascx and caseDefault.ascx, and dynamically load them to a page. Also you can use MVC to provide different actions depending to query string values.

Related

How Force browser to reload cached static file with versioning?

After deploying a new version of a website the browser loads everything from its cache from the old webpage until a hard, force refresh is done.
In ASP.NET MVC if the file becomes in Bundle, it handled by Optimization framework. a version added to your file link, and if a change occurs in your bundle's file a new token generate. follow below code :
for example, js file name is: datatables
when you put it in a bundle with the same name, you will see the
datatables?v=anY9_bo7KitrGnXQr8ITP3ylmhQe9NDzSjgLpLQWQFE1
as a file name.
change datatables and watch again the name of the file in the browser, surely it will change:
datatables?v=r8yhQBxKyDgrOGyqr1ndtdG92Ije09nqTY7yogrOSTk1
But there's two questions:
What we can do if our file wasn't in Bundle?
Is a way to force the browser to refresh cache?
we have one solution with some different way for implementation. we use above solution for it.
datatables?v=1
we can handle the version of the file, it's mean that every time that we change our file, change the version of it too. but it's not a suitable way.
another way used Guide, it wasn't suitable too, because each time it fetches the file and doesn't use from the browser cache.
datatables?v=Guid.NewGuid()
The last way that is the best Way is :
when file change occur , change version too. check follow code :
<script src="~/scripts/main.js?v=#File.GetLastWriteTime(Server.MapPath("/scripts/main.js")).ToString("yyyyMMddHHmmss")"></script>
by this way, when you change the file, LastWriteTime change too, so the version of the file will change and in the next when you open the browser, it detects a new file and fetch it.
Assuming you cannot use bundling for some reason, the solution suggested by the original poster is good enough, however it's better to put the logic inside a helper method.
It makes the code testable, it helps to change the logic without changing .cshtml , and also helps to not repeat the filename twice. Then you can have have a much cleaner code:
<script src="#Url.ContentWithVersion("~/scripts/main.js")"></script>
To do so, you can add ContentWithVersion extension method to the existing UrlHelper:
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
public static class UrlHelperExtensions
{
public static string ContentWithVersion(this UrlHelper urlHelper, string path)
{
if (urlHelper == null)
throw new ArgumentNullException(nameof(urlHelper));
var result = urlHelper.Content(path);
var file = HttpContext.Current.Server.MapPath(path);
if (File.Exists(file))
result += $"?v={File.GetLastWriteTime(file).ToString("yyyyMMddHHmmss")}";
return result;
}
}

How to extend vbscript with C#

I would like to extend the functionality of vbscript with the code I have written in c#. I have written some classes to automate the SAP GUI and would like to use these classes in all the vbscript files I have.
I have hundreds of vbscript files and know it will take years to convert all them to C#. So I think it will be faster to expose my c# classes to vbscript.
Do you know how to do this or know any references online I can study?
I don't know whether you're running your VBScript from the command-line or from within something like Office.
If the former, you could create one or more command-line apps that you can call from any scripting language and into which you pass parameters & action specifiers just like any other command-line tool. (Also consider moving to PowerShell in this case - it exponentially better than VBScript for command-line scripting & has great integration with .NET).
If the latter, you'll likely need to register your C# classes using RegAsm and then create instances of your C# types as per any other COM type. See this post for more details: How do I call .NET code (C#/vb.net) from vbScript?
VB script runs on the client inside the browser run-time.
The only C# solution I am aware of to run inside the browser, is silverlight. It is still just c# though.
You can access c# code from scripting languages like VB- of java-script, by decorating them with the [ScriptableMember] attribute, like so:
/// <summary>
/// Members that can be called from javascript. (or vbscript)
/// </summary>
public sealed class LINEARVIEWER_SL_SCRIPTS {
[ScriptableMember]
public void ChangeNetwork(string pNetworkFilterId, string pNetworkFilter) {
MainViewModel MainVM = (MainViewModel)((MainPage)Application.Current.RootVisual).DataContext;
long SectionID;
if (long.TryParse(pNetworkFilterId, out SectionID) == false) {
throw new FormatException("'" + pNetworkFilterId + "' not a valid section / network ID.");
}
MainVM.RoadFilterViewModel.SelectSectionAsync(SectionID, /* completed handler = */ null);
}
}
You have to register these classes when the silverligh (c#) application starts up, like so:
private void Application_Startup(object sender, StartupEventArgs e) {
...
HtmlPage.RegisterScriptableObject("LINEARVIEWER_SL_SCRIPTS", new LINEARVIEWER_SL_SCRIPTS());
}
From the java (or vb) script, you can then simply call those methods like so:
function DoAddToLIV(pNetworkFilterId, pNetworkFilter) {
...
gObjLIV.Content.LINEARVIEWER_SL_SCRIPTS.ChangeNetwork(pNetworkFilterId, pNetworkFilter);
...
}
where gObjLIB.Content is the id of the silverlight object inside the html page.
var gObjLIV = null;
function onSilverlightPluginLoaded(sender, args) {
gObjLIV = sender.getHost();
}
You can hook that function to the silverlight object in the html of ASPX page, using this parameter:
<param name="onLoad" value="onSilverlightPluginLoaded" />
Let me know if I missed anything or if you need more examples. I don't mind.

How to load referenced script libraries from a Roslyn script file?

I figured out I cannot load one script library from another easily:
module.csx
string SomeFunction() {
return "something";
}
script.csx
ExecuteFile("module.csx");
SomeFunction() <-- causes compile error "SomeFunction" does not exist
This is because the compiler does not know of module.csx at the time it compiles script.csx afaiu. I can add another script to load the two files from that one, and that will work. However thats not that pretty.
Instead I like to make my scripthost check for a special syntax "load module" within my scripts, and execute those modules before actual script execution.
script.csx
// load "module.csx"
SomeFunction()
Now, with some basic string handling, I can figure out which modules to load (lines that contains // load ...) and load that files (gist here https://gist.github.com/4147064):
foreach(var module in scriptModules) {
session.ExecuteFile(module);
}
return session.Execute(script)
But - since we're talking Roslyn, there should be some nice way to parse the script for the syntax I'm looking for, right?
And it might even exist a way to handle module libraries of code?
Currently in Roslyn there is no way to reference another script file. We are considering moving #load from being a host command of the Interactive Window to being a part of the language (like #r), but it isn't currently implemented.
As to how to deal with the strings, you could parse it normally, and then look for pre-processor directives that are of an unknown type and delve into the structure that way.
Support for #load in script files has been added as of https://github.com/dotnet/roslyn/commit/f1702c.
This functionality will be available in Visual Studio 2015 Update 1.
Include the script:
#load "common.csx"
...
And configure the source resolver when you run the scripts:
Script<object> script = CSharpScript.Create(code, ...);
var options = ScriptOptions.Default.WithSourceResolver(new SourceFileResolver(new string[] { }, baseDirectory));
var func = script.WithOptions(options).CreateDelegate()
...

Run javascript in C# WPF Form

*Please note that this is not for a web based application, it's windows based.
I'm building an application where I will need the user to submit simple javascripts that will be run by the application.
The scripts will call functions that are part of the c# build.
An example:
C# code:
public void helloWorld()
{
Debug.WriteLine("hello world");
}
Javascript submitted by user:
helloWorld();
The JavaScript would be parsed by the application at runtime and then call the required functions in my C# code.
Why?..
My app will be used by people with very little programming experience, they enter very simple JavaScripts and the app will attempt to automate a few tasks on the users computer. So my reason for using JavaScript is because it's simple and very easy to learn for someone with little experience.
It sounds like you want a JavaScript parser for your application. To be honest, I dont think what you're doing is possible, considering the context of the script and your code is different. However, this project seems to be doing something that may get you to the right place:
http://javascriptdotnet.codeplex.com/
Personally, I would think making some kind of XML format would be useful (like how UrlRewriter.net makes rewriting URLs easy):
<xml>
<commands>
<!-- Expose a Set of Condition Objects to Select From -->
<if condition="YourApplication.Conditions.RightClickOnDesktop">
<print text="HelloWorld" />
</if>
</commands>
Here is an example running a javascript code which, in turn, invokes a c# method
[System.Runtime.InteropServices.ComVisible(true)]
public class CSharpClass
{
public void MsgBox(string s)
{
MessageBox.Show(s);
}
}
-
Type scriptType = Type.GetTypeFromCLSID(Guid.Parse("0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC"));
dynamic obj = Activator.CreateInstance(scriptType, false);
obj.Language = "Javascript";
obj.AddObject("mywindow", new CSharpClass(), true);
var result = obj.Eval(
#"
function test(){
mywindow.MsgBox('hello');
}
test();
"
);
Why do you "need the user to submit simple javascripts"? What is your application and what do users need it to do? Why have you decided a scripting language is the way to do this? I'm not saying that is the wrong answer, but that you have not justified this conclusion.
If your app will be used by "people with very little programming experience" I do not recommend implementing a scripting language. Basic concepts like source code and variables are very difficult for non-programmers to understand.
I suggest first investigating macro recording for user scripting. For .NET there is UI Automation and the White automation framework.

Why do 'requires' statements fail when loading (iron)ruby script via a C# program?

IronRuby and VS2010 noob question:
I'm trying to do a spike to test the feasibility of interop between a C# project and an existing RubyGem rather than re-invent that particular wheel in .net. I've downloaded and installed IronRuby and the RubyGems package, as well as the gem I'd ultimately like to use.
Running .rb files or working in the iirb Ruby console is without problems. I can load the both the RubyGems package, and the gem itself and use it, so, at least for that use case, my environment is set up correctly.
However, when I try to do the same sort of thing from within a C# (4.0) console app, it complains about the very first line:
require 'RubyGems'
With the error:
no such file to load -- rubygems
My Console app looks like this:
using System;
using IronRuby;
namespace RubyInteropSpike
{
class Program
{
static void Main(string[] args)
{
var runtime = Ruby.CreateRuntime();
var scope = runtime.ExecuteFile("test.rb");
Console.ReadKey();
}
}
}
Removing the dependencies and just doing some basic self-contained Ruby stuff works fine, but including any kind of 'requires' statement seems to cause it to fail.
I'm hoping that I just need to pass some additional information (paths, etc) to the ruby runtime when I create it, and really hoping that this isn't some kind of limitation, because that would make me sad.
Short answer: Yes, this will work how you want it to.You need to use the engine's SetSearchPaths method to do what you wish.
A more complete example
(Assumes you loaded your IronRuby to C:\IronRubyRC2 as the root install dir)
var engine = IronRuby.Ruby.CreateEngine();
engine.SetSearchPaths(new[] {
#"C:\IronRubyRC2\Lib\ironruby",
#"C:\IronRubyRC2\Lib\ruby\1.8",
#"C:\IronRubyRC2\Lib\ruby\site_ruby\1.8"
});
engine.Execute("require 'rubygems'"); // without SetSearchPaths, you get a LoadError
/*
engine.Execute("require 'restclient'"); // install through igem, then check with igem list
engine.Execute("puts RestClient.get('http://localhost/').body");
*/
Console.ReadKey();

Categories