When writing Javascript code within a Razor/cshtml file, one may write code as follows:
if (lSelectedID == "#(Globals.MyGlobalVariable)") {
...
}
where Globals.MyGlobalVariable is a C# variable.
If Globals.MyGlobalVariable==123, then the resulting Javascript on the client will be
if (lSelectedID == "123") {
...
}
The above is very handy. But how to do the same in Typescript? I.e. how to insert a C# global variable (or result of C# function call or whatever) into typescript before the typescript file is transformed to Javascript?
It's not best practice to include JavaScript and CSS directly into your CSTHML. Rather you should have them in their own file and reference them in your view.
If your JavaScript is going to need some value from C# then you should store it by using data attribute in your HTML elements.
Example:
<span id="myGlobalVariable" data-value="123456">MyGlobalVariable</span>
Then in your TypeScript get data you have set in your View
let myGlobalVariable = document.getElementById("myGlobalVariable").dataset.value;
if (lSelectedID == myGlobalVariable) {
}
I think the easiest thing to do here would be to replicate your global variables in Typescript on the client side. This is how I've done it for my last two projects.
So on the server side you would have:
// C#
public class Globals()
{
public int GlobalNum {get;} = 0;
public string GlobalString {get;} = "123";
}
And on the client side, in Typescript it would be:
// Typescript
export enum Globals{
GlobalNum = 0;
GlobalString = "123";
}
Now you can forget about the difficulty of trying to connect Razor (which renders server-side) to your Typescript (which executes on the client side), while still having a clear and obvious set of globals to refer to.
You code can then become:
// Typescript
if (lSelectedID == Globals.GlobalString) {
//...
}
The only thing you need to keep in mind is that your global variables exist in two places - once on the server side and once on the client side.
Typescript demands that you replicate a lot of your server-side classes on the client side anyway, for receiving fetch response data properly, for example, so the addition of a Globals class/enum should not be too much of a break from the norm.
Related
Is there any way to run the PHP code on the c# app
since I'm working on an application that requires to implement of this site's API
but there is no documentation except for PHP, so is there any way I can use this piece of code in a c# application or convert this code in C# if that is possible.
public $api_url = 'https://smm-bomb.com/api/v2'; // API URL
public $api_key = ''; // Your API key
public function order($data) { // add order
$post = array_merge(array('key' => $this->api_key, 'action' => 'add'), $data);
return json_decode($this->connect($post));
}
One option is to rewrite the call using C#, check docs if needed.
Another one is to made your custom php-api which wrap initial call.
Then from C# just use your php-api. Postman can be a useful tool to check your custom php-api and also for C# code generation
---custom php-api---
--update to fit https://smm-bomb.com/api--
<?php
class Api
{
public $api_url = 'https://smm-bomb.com/api/v2'; // API URL
public $api_key = '4a99333333333333333dummy'; // Your API key
...
//just copy-paste from example
}
//from-docs, create an instance an invoke any methods
//since it's a self contained class no imports required
//main
$api = new Api();
$services = $api->services(); # return all services
$out = [];
//mainly here will be the return of api-call
$out["mykey"]="myvalue";
//output as json whatever wanted
$out["listServices"]=$services;
echo json_encode($out);
?>
//sample output
//{"mykey":"myvalue"}
This piece of code should be accessible via link eg: https://yoursite/custom-api (for security purpose can use a token on query-string. /custom-api?key=123mykey ->trivial approach)
Use PostMan to check and see code-generation
I am new to C# and Razor v3.
I have a php web app that I am trying to convert to ASP.NET. I decided, mainly due to ease, to use Razor. What I am making is a Single Page App.
The way I have it laid out in PHP is via 3 php files, 1 of which essentially passes the variable values to the main index.php like so, for example
vars.php
if (isset($_GET["lang"])) {
$lang = mb_strtolower($_GET["lang"]);
} else {
$lang = "el";
}
and this is how my index.php uses that variable
<html lang=<?php echo "\"".$lang."\"";if($page2go===1) {echo " itemscope itemtype=\"http://schema.org/Article\"";}?>>
Now, everytime index.php is called, I call on vars.php by using
<?php require_once('./scripts/vars.php');?>
This is how my values are passed into my index.php.
I have found I can do the similar by including my if statements and variable delcarations at the top of my index.cshtml. Like so
#{
var lang = "";
if (!String.IsNullOrEmpty(Request.QueryString["lang"]))
{
var interior = Request.QueryString["lang"];
interior.ToLower();
lang = interior;
}
else
{
lang = "el";
}
}
Now I perform a LOT of if operations like that, making my index.cshtml an absolute mess.
Is there a way to pass the variable values, like I do in php by including vars.php?
Thanks a lot for your time.
You should recreate your one-page application to an MVC application.
All the request processing (and other complex logic) will take place in the controller action.
The controller action will in turn pass all variables that you need to the view that you have created.
I have this in my web.config
If this value is live, then I want to call the live web service, and if it's not, then I want to call the test web service.
In my code I want to do something like this:
if (System.Configuration.ConfigurationManager.AppSettings["runMode"] == "live")
{
var client = new CallStatusAvailability.ServiceReference1
.StatusAvailabilityRoomsClient();
}
else
{
var client = new CallStatusAvailability.StatusAvailabilityRooms
.StatusAvailabilityRoomsClient();
}
using (client)
{
...... lots of logic
}
The problem is that client is out of scope. I would like to be able to declare client before the if statement, but not sure what I can define it as?
I could put the using statement within the if or the else statement, but I would then have to duplicate all the logic in both.
At first I tried to create a function that could be called from the if and the else, and pass in client, but then I face the same issue of what type to declare the input client variable as, as an input to the function.
I would suggest that you not add both service references to your project, but a single service reference (probably to the test service) and vary the connection parameters using configuration transforms. You would do this by setting your base web.config up to connect to the test service, then add a transform in web.Release.config to change the binding when deployed using the Release target. This will simplify your logic to the point where you won't need the if-else construct and allow you to create the client within a using statement.
Your issue is that var is declaring a variable. If you need to use a variable in this way you can't use var as it need to be declared at a higher level of scope. Just move your declaration to the containing block. This assumes the service references are using the same type; if not, you need to fix that first or use dynamic if they are semantically identical. You also can't use a using in this context and must use try catch finally.
To use the same types I would suggest generating the proxy using the channel factory or using svcutil so that your types are the same for the different service references.
CallStatusAvailability.ServiceReference1.StatusAvailabilityRoomsClient client = null;
try
{
if (System.Configuration.ConfigurationManager.AppSettings["runMode"] == "live")
{
client = new CallStatusAvailability.ServiceReference1.StatusAvailabilityRoomsClient();
}
else
{
client = new CallStatusAvailability.StatusAvailabilityRooms.StatusAvailabilityRoomsClient();
}
}
catch(..){}
finally
{
client.Dispose();
}
I have a silver-light based web application.I am using ScriptObject to connect and call method in java script and in turn java script interact with plugin. All the function call from c# to java script was synchronous.now Now I am trying to use web socket server for replacement for plugin.
Now I am just changing the code of the methods in java script file to interact with web socket server.
Since web Socket call are asynchronous in nature I am not able to implement the call from c# to java script and return value.
Now I wanted call callback from java script to c# code.Is this is possible ?
Please suggest how to solve this problem.
It's possible.
You annotate a class like this:
public class MyScriptableManagedType {
[ScriptableMember()]
public string MyToUpper(string str) {
return str.ToUpper();
}
[ScriptableMember()]
public string Name { get; set; }
}
put it in the page's scope of javascript objects:
MyScriptableManagedType smt = new MyScriptableManagedType();
HtmlPage.RegisterScriptableObject("mySLapp", smt);
Then you can use it from javascript like so:
var slCtl = null;
function pluginLoaded(sender,args){
slCtl = sender.getHost();
alert(slCtl.Content.mySLapp.MyToUpper("Test String"));
}
The function pluginLoaded has to be registered with the silverlight plugin to be called on load.
Take from and more details at:
http://msdn.microsoft.com/en-us/library/cc221414(v=vs.95).aspx
I have two separate servers with identical WCF services (let's say, WS1 and WS2) and a C# Mobile CF 2.0 project that need to access both of the services.
Can I do something like this on the C# CF2.0 project?
(...)
if (someCondition == true)
{
WS1 aux = new WS1();
}
else
{
WS2 aux = new WS2();
}
aux.service(parameter1);
(...)
note that I want to have the same variable name, independent of which server I'll access. The problem is: I don't know how to declare it outside the conditional statements and when I just declare it inside the conditional statements they're declared as local variables and I don't know how to make the variable public or global.
Any thoughts or help, please?
Since the WCF Service is exactly the same, just running on different servers, then from your client project simply add a service reference to one of them (WS1 for example). This will generate the client proxy for you. Perhaps give it a generic name too, like "serviceX" (replacing X with something appropriate for your application).
Then, in your client config file, copy the client endpoint it created and add another endpoint with the only difference being the address and the endpoint name. Maybe you want to set the endpoint name property on each endpoint to be "WS1" and "WS2" respectively.
Then, in your code, you should be able to do something like this:
(...)
serviceXClient aux = null;
if (someCondition == true)
{
aux = new serviceXClient("WS1");
}
else
{
aux = new serviceXClient("WS2");
}
aux.service(parameter1);
(...)
If you're using .Net 4.0 or higher you could use dynamic typing.
http://msdn.microsoft.com/en-us/library/dd264736.aspx