How to connect SignalR Client on mobile device - javascript

Now i am developing selfhost signalr server application using VS2012 and client application using HTML/JS WebUI in Mosync IDE. When communication between client and server application, the signalr hub is successfully created on all browser and android emulator. But its doesn't work when i am using USB Debugging on my mobile. its produce 'undefined' message. How to make successful connection on my mobile. Please guide me.
Server side code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.Owin.Hosting;
using Microsoft.Owin.Cors;
using Microsoft.Owin;
using Owin;
namespace SignalRServer
{
public partial class Form1 : Form
{
private IDisposable signalR { get; set; }
public string ServerURI;
MyNewHub h = new MyNewHub();
public Form1()
{
InitializeComponent();
}
private void btnStart_Click(object sender, EventArgs e)
{
writeToConsole("Starting server...");
btnStart.Enabled = false;
Task.Run(() => StartServer());
}
private void StartServer()
{
try
{
//signalR = WebApp.Start(ServerURI);
if (File.Exists(Application.StartupPath + "\\IPAddress.txt"))
{
ServerURI = System.IO.File.ReadAllText(Application.StartupPath + "\\IPAddress.txt").Trim();
signalR = WebApp.Start(ServerURI);
}
else
{
MessageBox.Show("IPAddress not found");
}
}
catch (TargetInvocationException)
{
writeToConsole("Server failed to start. A server is already running on" + ServerURI);
this.Invoke((Action)(() => btnStart.Enabled = true));
return;
}
this.Invoke((Action)(() => btnStart.Enabled = true));
writeToConsole("Server started at" + ServerURI);
}
public void writeToConsole(string message)
{
if (RichTextBoxConsole.InvokeRequired)
{
this.Invoke((Action)(() => writeToConsole(message)));
return;
}
RichTextBoxConsole.AppendText(message + Environment.NewLine);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (signalR != null)
{
signalR.Dispose();
}
}
private void btnSend_Click(object sender, EventArgs e)
{
string msg = txtMesage.Text;
h.Receive(msg);
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
[HubName("myNewHub")]
public class MyNewHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);
Program.mainform.writeToConsole(name + " : " + message);
}
public void Receive(string msg)
{
var context = GlobalHost.ConnectionManager.GetHubContext<MyNewHub>();
context.Clients.All.addMessage("Admin", msg);
}
public override Task OnConnected()
{
Program.mainform.writeToConsole("Client Connected:" + Context.ConnectionId);
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
Program.mainform.writeToConsole("Client DisConnected: " + Context.ConnectionId);
return base.OnDisconnected(stopCalled);
}
}
}
Client side code:
<!DOCTYPE html>
<!--
* #file index.html
*
* Template application that shows examples of how to access
* device services from JavaScript using the Wormhole library.
-->
<html>
<head>
<title>SignalR Simple Chat</title>
<style type="text/css">
.container {
background-color: #99CCFF;
border: thick solid #808080;
padding: 20px;
margin: 20px;
}
</style>
<meta name="viewport" content="width=320, user-scalable=no">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Wormhole Template App</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" title="no title" charset="utf-8">
<script type="text/javascript" charset="utf-8" src="js/wormhole.js"></script>
<script src="js/jquery-1.6.4.min.js"></script>
<script src="js/jquery.signalR-2.0.3.min.js"></script>
<script src="http://192.168.0.7:8080/signalr/hubs"></script>
<script type="text/javascript">
function clientconnect()
{
alert("Start Button Clicked");
$.connection.hub.url = "http://192.168.0.7:8080/signalr";
// Declare a proxy to reference the hub.
var chats = $.connection.myNewHub;
alert(chats);
// Create a function that the hub can call to broadcast messages.
chats.client.addMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chats.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
}
</script>
</head>
<body>
<div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<input type="button" value="Start" onclick="clientconnect()"/>
<ul id="discussion"></ul>
</div>
</body>

Related

Spring Controller not returning a html page after an Ajax get Request

So I have a "discount" html page, where a user is prompted to enter a promo code, by using an Ajax GET request from the buttons OnClick, I am able to transfer this promo code to my spring controller, where I manipulate the data appropriately.
For some reason I am unable to "return" a new page from this controller, I do not get any noticeable errors on my server side but on my client side I get this error:
I am not sure if this is related or relevant.
I was wondering is my logic behind this flawed or am I not implementing the correct syntax to return a new page after the AJAX call.
Note: The AJAX request works fine as I am able to get a system.out.print to the console at the bottom of the controller with the relevant info. that I passed.
Here is my html code:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1"></meta>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"></link>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
function myFunction(){
var code = document.getElementById("code").value;
var price = document.getElementById("price").value;
$.ajax({
type: "GET",
url: "/calculateDiscount",
data: {
code: code
}, // parameters
contentType: "application/json; charset=utf-8",
datatype: 'json'
//alert(status);
});
}
</script>
</head>
<body>
<div>
<center>
<h3>Total Price: $<text th:text="${totalPrice}" id="price"/> </h3>
<input type="text" name="firstname" id="code">
<button onclick="myFunction()">Calculate Discount</button>
<a style="color:blue" th:href="#{/welcome}">HomeScreen!</a>
<br />
<!-- <a style="color:blue" th:if="${myteam != null}" th:href="#{/leaveteam/{id}(id=${myteam?.id})}">Leave Team?!</a>
-->
</center>
</div>
</body>
</html>
Controller:
#RequestMapping(value="/calculateDiscount", method=RequestMethod.GET)
#ResponseBody
public String CalculateDiscount(Model model, #RequestParam("code") String code, RedirectAttributes redirectAttributes) {
///need to calculate price if codes correct then return page with card info then after proceed call purchasebooks controller!
System.out.println("Price: " + code );
Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
String email = loggedInUser.getName();
UserLogin user = uR.findByUserName(email);
int totalPrice = 0;
if (code.equals("Discount1010"))
{
Set<Book> books = user.getBooks();
for (Book b : books)
{
totalPrice = totalPrice + b.getPrice();
}
int discountPrice = (int) (totalPrice * .80);
model.addAttribute("totalPrice", totalPrice);
System.out.println("Price: " + discountPrice );
}
else {
Set<Book> books = user.getBooks();
for (Book b : books)
{
totalPrice = totalPrice + b.getPrice();
}
System.out.println("Price: " + totalPrice );
model.addAttribute("totalPrice", totalPrice);
}
return "payment";
}
The page I am trying to return:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1"></meta>
<title>Insert title here</title>
</head>
<body>
<h3>Total Price: $<text th:text="${totalPrice}" id="price"/> </h3>
</body>
</html>
Any more info needed let me know.
K.
EDIT: In response to one of the answers below, I do have csrf disabled.
Here is my WebSecurityConfig class:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
UserLoginRepository userLoginRepository;
//http.authorizeRequests().antMatchers("/", "/home", "/registeruser").permitAll().antMatchers("/admin").hasRole("ADMIN")
#Autowired
DataSource dataSource;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/home", "/registeruser").permitAll().antMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout()
.permitAll();
http.exceptionHandling().accessDeniedPage("/403");
http.csrf().disable();
//disable csrf to allow communication (we also dont need for this fyp as its not live)
}
#Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/fonts/**", "/images/**", "/css/**");
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select user_name,password,user_status from user_login where user_name=?")
.authoritiesByUsernameQuery("select user_name, password from user_login where user_name=?");
}
#Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}
}
Update: #ResponseBody annotation was added to the controller method, problem still persists
I guess this is CSRF problem. You have Spring Security implemented (I can see
SecurityContexHolder class) and probably csrf enabled - this is default setting. If you want to disable it just use this
Java configuration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
XML:
<http>
<!-- ... -->
<csrf disabled="true"/>
</http>
But if you want to keep csrf enabled, you need to pass csrf token to ajax header. To do this, include csrf to meta tag:
<head>
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
And then include csrf to Ajax request:
var token = /*[[${_csrf.token}]]*/ '';
var header = /*[[${_csrf.headerName}]]*/ '';
$(document).ajaxSend(function(e,xhr,options) {
xhr.setRequestHeader(header, token);
});

link html button to java activity

I'm making an Android app to my book I have an html page I want to add a button on it which is linked to this Java code
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// listeners of our two buttons
View.OnClickListener handler = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonShareTextUrl:
shareTextUrl();
break;
}
}
};
// our buttons
findViewById(R.id.buttonShareTextUrl).setOnClickListener(handler);
}
// Method to share either text or URL.
private void shareTextUrl() {
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("text/plain");
share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
// Add data to the intent, the receiving app will decide
// what to do with it.
share.putExtra(Intent.EXTRA_SUBJECT, "book");
share.putExtra(Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=com.sohaibm.assrar_bac");
startActivity(Intent.createChooser(share, "share with"));
}
}
so I want you to give me an HTML code of the page that contains the button linked to this activity and thank you so much
If you use WebView to show book content you can use WebViewClient:
WebViewClient mWebClient = new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.startsWith("handle:")){
// do something
return true;
}
else{
view.loadUrl(url);
}
return true;
}
};
mWebView.setWebViewClient(mWebClient);
And your link should be:
Link text
Try like this:
Html Page:
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript">
function moveToScreenTwo() {
Android.moveToNextScreen();
}
</script>
</head>
<body>
<div>
<input type="button" value="Locate" onClick="moveToScreenTwo()" />
</div>
</body>
</html>
FirstACtivity.java:
import android.webkit.JavascriptInterface;
webView = (WebView) findViewById(R.id.load_url);
webView.getSettings().setJavaScriptEnabled(true);
if (new File(url).exists()) {
webView.loadUrl(FILENAME_PREFIX + url);
Log.d("fileurl", "" + FILENAME_PREFIX + url);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
}
//Class to be injected in Web page
public class WebAppInterface {
Context mContext;
/**
* Instantiate the interface and set the context
*/
WebAppInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public void moveToNextScreen() {
Intent i = new Intent(FirstActivity.this,SecondActivity.class);
startActivity(i);
}
}
For more Reference: Check this tutorial.

How to call cordova plugin action synchronously in Button click in javascript

How to call cordova plugin action synchronously in Button click in java script
We need to upgrade every javascript annotation method to plugin format with synchronously.
Java - Our own plugin
public class ProjectUtility extends CordovaPlugin{
public static final String TAG = " Project Utility";
private final static String characterEncoding = "UTF-8";
DataMgnt dm = new DataMgnt();
public CordovaInterface cordovaInterface;
public ProjectUtility() {
System.out.println(" project utility");
}
/**
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* #param cordova The context of the main Activity.
* #param webView The CordovaWebView Cordova is running in.
*/
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
cordovaInterface=cordova;
Log.v(TAG,"Init CoolPlugin dsfsdf" +cordova.getActivity().getString(R.string.app_name));
}
public boolean execute(final String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
final int duration = Toast.LENGTH_SHORT;
// Shows a toast
Log.v(TAG,"CoolPlugin received: dsfsdfdssdadfa"+ action);
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
Toast toast = Toast.makeText(cordova.getActivity().getApplicationContext(), cordovaInterface.getActivity().getString(R.string.app_name), duration);
toast.show();
if(action.equals("imei"))
{
callbackContext.success(getImeiNumber());
}
else if(action.equals("app_name")){
callbackContext.success(appName());
}
else if(action.equals("service_id")){
callbackContext.success(getServiceId());
}
else
{
callbackContext.error("fail");
}
}
});
return true;
}
public String getImeiNumber()
{
TelephonyManager tm = (TelephonyManager) cordovaInterface.getActivity().getSystemService(Context.TELEPHONY_SERVICE);
String imeiId="";
try{
imeiId = tm.getDeviceId();
}
catch(Exception e)
{
imeiId="null";
e.printStackTrace();
}
return "12364589785451";
}
String getServiceId()
{
String service_id= cordovaInterface.getActivity().getString(R.string.service_id);
return service_id;
}
public String appName()
{
return cordovaInterface.getActivity().getString(R.string.app_name);
}
}
javascript :
utlity.js
We initialize common funtion to access the plugin:
window.sdpproperty = function(key,arg_array ,callback) {
cordova.exec(callback, function(err) {
callback('error');
}, "ProjectUtility", key,arg_array);
};
index.html – we accessing window.property function,
This file contain two functions,
1) we_need_like_this()
2) but_it_work_like_this_no_need_this_format()
3) sample
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>Hello World</title>
<script>
function we_need_like_this() {
var service_id,
imei;
window.sdpproperty("service_id", [], function (echoValue) {
service_id = echoValue;
alert("Inside Inside the call back exec the service id " + echoValue)
});
window.sdpproperty("imei", [], function (echoValue) {
imei = echoValue;
alert("Inside call back exec the imei " + echoValue)
});
sample(service_id, imei)
}
function sample(service_id, imei) {
alert("Inside the Sample func. Service Id " + service_id + " Imei " + imei);
}
function but_it_work_like_this_no_need_this_format() {
var service_id,
imei;
window.sdpproperty("service_id", [], function (echoValue) {
service_id = echoValue;
window.sdpproperty("imei", [], function (echoValue) {
imei = echoValue;
sample(service_id, imei)
});
});
}
</script>
</head>
<body>
<div class="app">
<div id="deviceready" class="blink">
<p class="event listening">..... App Loading....</p>
</div>
<button onclick="we_need_like_this()">We Need</button>
<button onclick="but_it_work_like_this_no_need_this_format()">We no Need</button>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/utlity.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.4.5.js"></script>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
</body>
</html>
As of Cordova Plugins dev docs the JS interface must have:
cordova.exec(function(winParam) {},
function(error) {},
"service",
"action",
["firstArgument", "secondArgument", 42, false]);
and your definition has:
cordova.exec(callback,
function(err) { callback('error'); },
"ProjectUtility",
key,
arg_array);
so the parameter key is the action to be executed on the native side.
Examining your JAVA file the actions available are these:
authencation_hash_encrypt <---- PAY ATTENTION THERE IS A TYPO!
service_id
authencation_encrypt <---- PAY ATTENTION THERE IS A TYPO!
authentication_hash_decrypt
decrypt_value
decrypt
authent_token
new_decrypt
authencation_hash_encrypt <---- PAY ATTENTION THERE IS A TYPO!
encrypt_value
encrypt_hash
So the value "key_cre" as key parameter is not present...

desktop notification using javascript in windows form

i am new to this and i am creating simple application in which i click a button and a notification on desktop should be displayed. i am doing this in windows form c#
the error is " NullReferenceException was unhandled
i have one button Notify in form1. i have tried this:
form1.cs
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
webBrowser1.ScriptErrorsSuppressed = true;
}
private void btnNotify_Click(object sender, EventArgs e)
{
webBrowser1.Document.InvokeScript("notifyMe");
}
private void Form1_Load(object sender, EventArgs e)
{
string CurrentDirectory = Directory.GetCurrentDirectory();
webBrowser1.Navigate(Path.Combine(CurrentDirectory,"HTMLPage1.html"));
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.ObjectForScripting = this;
code for HTMLPage1.html :
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script language="javascript" type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
if (Notification.permission !== "granted")
Notification.requestPermission();
});
function notifyMe() {
if (!Notification) {
alert('Desktop notifications not available in your browser. Try Chromium.');
return;
}
if (Notification.permission !== "granted")
Notification.requestPermission();
else {
var notification = new Notification('Notification title', {
icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
body: "Hey there! You've been notified!",
});
notification.onclick = function () {
window.open("http://stackoverflow.com/a/13328397/1269037");
};
}
}
</script>
</head>
<body>
</body>
</html>
even if i simply put alert("Hi") in notifyMe() function, nothing else. still it displays the same error.
I have tried your code.. you should use
document.attachEvent('DOMContentLoaded', function () {..
Instead of
document.addEventListener("..
That worked from here...read more about it here https://stackoverflow.com/a/1695383/4155741
you should also remove that comma at the end of .. body: "Hey there! You've been notified!", as it prevent the script from be compiled.
You have to put your html and scripts in the debug directory if they are not automatically placed. Thats where getcurrentdirectory() hits.

Converting Serverside C# to ASP.NET Web API

After posting on how to get server side information to JS (on client side) link here, I was advised to create my server side logic into a Web Api in order to expose data via HTTP through a JQuery AJAX call. After looking through a lot of documentation, and even a tutorial series online hosted by Microsoft, I found little to no good instruction. Previously, I was calling my serverside methods through inline C# calls in my js script, but learned that because C# is precompiled, it simply just "fills in" the values returned by the C# functions.
Just for a reference as to how I am improperly calling my C# methods.
This is my front end: Login.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>PAM testing</title>
<link rel="stylesheet" type="text/css" href="Styles/Site.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="Scripts/JScript.js"></script>
</head>
<body>
<div id="banner">PAM Testing Tool</div>
<div id="content">
<form id="form1" runat="server" style="margin-left: 25%; text-align: center; height: 41px; width: 292px;">
<%--Login ASP Object--%>
<asp:Login ID="Login1" runat="server" onclick="process()"></asp:Login>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" style="text-align: center" ValidationGroup="Login1" />
</form>
<%--TEST AREA--%>
<script type="text/javascript">
function logCookie(){
document.cookie = "user=" + document.getElementById("Login1_UserName").value;// this is the id of username input field once displayed in the browser
}
function testFunction() {
<%=Login1_Authenticate() %>;
}
function process(){
logCookie();
testFunction();
}
</script>
</div>
</body>
</html>
My C# code looks like this
Login.aspx.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.EnterpriseServices;
public partial class Login : System.Web.UI.Page
{
int status;
int role;
SqlConnection conn;
SqlCommand command;
SqlDataReader reader;
protected string Login1_Authenticate()
{
// create an open connection
conn =
new SqlConnection("Data Source=xxx;"
+ "Initial Catalog=xxx;"
+ "User ID=xxx;Password=xxx");
conn.Open();
//string userName;
//userName = Convert.ToString(Console.ReadLine());
// create a SqlCommand object for this connection
command = conn.CreateCommand();
command.CommandText = "EXEC dbo.SP_CA_CHECK_USER #USER_ID = '"+Login1.UserName+"', #PASSWORD = '"+Login1.Password+"'";
command.CommandType = CommandType.Text;
// execute the command that returns a SqlDataReader
reader = command.ExecuteReader();
// display the results
while (reader.Read())
{
status = reader.GetInt32(0);
}
// close first reader
reader.Close();
//----------
existTest();
return "the login process is finished";
}
public static string GetData(int userid)
{
/*You can do database operations here if required*/
return "my userid is" + userid.ToString();
}
public string existTest()
{
if (status == 0)
{
//login
Session["userID"] = Login1.UserName;
command.CommandText = "EXEC dbo.SP_CA_RETURN_USER_ROLE #USER_ID = '" + Login1.UserName + "'";
reader = command.ExecuteReader();
while (reader.Read())
{
role = reader.GetInt32(0);
}
Session["roleID"] = role;
if (Session["userID"] != null)
{
string userID = (string)(Session["userID"]);
//string roleID = (string)(Session["roleID"]);
}
Response.Redirect("Home.aspx");
}
else
{
//wrong username/password
}
// close the connection
reader.Close();
conn.Close();
return "process complete";
}
}
How can I convert my C# into Web api's? I would very much appreciate it if any answers could link me to good documentation or tutorials.
Moving this into Web API would require creating a new Web API project, setting up your appropriate controllers, and moving Form Control to parameters to pass into the Controller methods. Please visit this tutorial for more information on getting started with ASP.NET Web MVC: Getting Started With ASP-NET Web API
Please Note: Executing dynamic SQL the way you are doing in the above code leaves your application open to SQL Injection attacks! Please consider using parameterized SQL instead.

Categories

Resources