Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
20 views12 pages

APIS CODE Web Notes

The document contains code for a weather application using both RESTful and SOAP APIs, implemented in ASP.NET MVC. It includes controllers for fetching weather data from an external API and displaying it in views, as well as an ASMX web service for SOAP requests. Additionally, it features a banking system with models, controllers, and views for user registration, login, transactions, and account management.

Uploaded by

Humam Naveed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views12 pages

APIS CODE Web Notes

The document contains code for a weather application using both RESTful and SOAP APIs, implemented in ASP.NET MVC. It includes controllers for fetching weather data from an external API and displaying it in views, as well as an ASMX web service for SOAP requests. Additionally, it features a banking system with models, controllers, and views for user registration, login, transactions, and account management.

Uploaded by

Humam Naveed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

APIS CODE:

RESTFUL:

CONTROLLER:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using Newtonsoft.Json.Linq;

namespace APIS_1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}

public ActionResult GetWeather(string city)


{
if (string.IsNullOrWhiteSpace(city))
{
city = "London"; // Default city
}

string weatherUrl =
string.Format("https://goweather.herokuapp.com/weather/{0}",city);

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

using (var client = new WebClient())


{
var response = client.DownloadString(weatherUrl);
var data = JObject.Parse(response);

ViewBag.City = city;
ViewBag.Temp = data["temperature"];
ViewBag.Wind = data["wind"];
ViewBag.Description = data["description"];
}

return View();
}
}
}

VIEW:

@{
ViewBag.Title = "Weather App";
}

<h2>Weather Checker</h2>

<form method="post" action="/Home/GetWeather">


<input type="text" name="city" placeholder="Enter city name" required />
<button type="submit">Get Weather</button>
</form>
@if (ViewBag.City != null)
{
<h3>City: @ViewBag.City</h3>
<p>Temperature: @ViewBag.Temp</p>
<p>Wind: @ViewBag.Wind</p>
<p>Description: @ViewBag.Description</p>
}

SOAP:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml;

namespace APIS_1.Controllers
{
public class Home1Controller : Controller
{
public ActionResult Index()
{
return View();
}

public ActionResult GetWeatherFromSoap(string city)


{
if (string.IsNullOrWhiteSpace(city))
{
city = "London"; // Default
}

var service = new WeatherService();


XmlDocument weatherXml = service.GetWeather(city);//asmx maI YE
FUNCTION HOGA

// Extract data from XML


var cityName = weatherXml.SelectSingleNode("//City")?.InnerText;
var temperature =
weatherXml.SelectSingleNode("//Temperature")?.InnerText;
var wind = weatherXml.SelectSingleNode("//Wind")?.InnerText;
var description =
weatherXml.SelectSingleNode("//Description")?.InnerText;

ViewBag.City = cityName;
ViewBag.Temp = temperature;
ViewBag.Wind = wind;
ViewBag.Description = description;

return View();
}
}
}
VIEW:

@{
ViewBag.Title = "Weather App (SOAP)";
}

<h2>Weather Checker (Using SOAP + REST)</h2>

<form method="post" action="/Home1/GetWeatherFromSoap">


<input type="text" name="city" placeholder="Enter city name" required />
<button type="submit">Get Weather</button>
</form>

@if (ViewBag.City != null)


{
<h3>City: @ViewBag.City</h3>
<p>Temperature: @ViewBag.Temp</p>
<p>Wind: @ViewBag.Wind</p>
<p>Description: @ViewBag.Description</p>
}

ASMX CODE FOR APIS:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml;
using System.Net;
using Newtonsoft.Json.Linq;

namespace APIS_1
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WeatherService : WebService
{
[WebMethod]
public XmlDocument GetWeather(string city)
{
XmlDocument doc = new XmlDocument();

if (string.IsNullOrWhiteSpace(city))
{
city = "London";
}

// ✅ Live API call


string apiUrl = $"https://goweather.herokuapp.com/weather/{city}";

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

using (var client = new WebClient())


{
try
{
var response = client.DownloadString(apiUrl);
var data = JObject.Parse(response);
string temperature = data["temperature"]?.ToString() ??
"N/A";
string wind = data["wind"]?.ToString() ?? "N/A";
string description = data["description"]?.ToString() ??
"N/A";

// Create XML
string xml = $@"
<Weather>
<City>{city}</City>
<Temperature>{temperature}</Temperature>
<Wind>{wind}</Wind>
<Description>{description}</Description>
</Weather>";

doc.LoadXml(xml);
}
catch
{
// Error XML
string errorXml = $@"
<Weather>
<City>{city}</City>
<Temperature>Unknown</Temperature>
<Wind>Unknown</Wind>
<Description>Could not fetch data.</Description>
</Weather>";
doc.LoadXml(errorXml);
}
}

return doc;
}
}

}
MVC CODES

MODELS:
//----------------------------------------------------------------------------
--
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your
application.
// Manual changes to this file will be overwritten if the code is
regenerated.
// </auto-generated>
//----------------------------------------------------------------------------
--

namespace BankingSystem.Models
{
using System;
using System.Collections.Generic;

public partial class Admin


{
public int AdminId { get; set; }

public string Email { get; set; }


public string Password { get; set; }
}
}

//----------------------------------------------------------------------------
--
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your
application.
// Manual changes to this file will be overwritten if the code is
regenerated.
// </auto-generated>
//----------------------------------------------------------------------------
--

namespace BankingSystem.Models
{
using System;
using System.Collections.Generic;

public partial class Announcement


{
public int AnnouncementId { get; set; }
public string Title { get; set; }
public string Message { get; set; }
public Nullable<System.DateTime> DatePosted { get; set; }
}
}

//----------------------------------------------------------------------------
--
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your
application.
// Manual changes to this file will be overwritten if the code is
regenerated.
// </auto-generated>
//----------------------------------------------------------------------------
--

namespace BankingSystem.Models
{
using System;
using System.Collections.Generic;

public partial class Transaction


{
public int TransactionId { get; set; }
public Nullable<int> FromUserId { get; set; }
public Nullable<int> ToUserId { get; set; }
public Nullable<decimal> Amount { get; set; }
public Nullable<System.DateTime> Date { get; set; }
public string Type { get; set; }

public virtual User User { get; set; }


public virtual User User1 { get; set; }
}
}

//----------------------------------------------------------------------------
--
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your
application.
// Manual changes to this file will be overwritten if the code is
regenerated.
// </auto-generated>
//----------------------------------------------------------------------------
--

namespace BankingSystem.Models
{
using System;
using System.Collections.Generic;

public partial class User


{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage",
"CA2214:DoNotCallOverridableMethodsInConstructors")]
public User()
{
this.Transactions = new HashSet<Transaction>();
this.Transactions1 = new HashSet<Transaction>();
}

public int UserId { get; set; }


public string FullName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public Nullable<decimal> Balance { get; set; }
public string BankName { get; set; }

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage",
"CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Transaction> Transactions { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage",
"CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Transaction> Transactions1 { get; set; }
}
}

CONTROLLERS:

ACCOUNT:
using BankingSystem.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BankingSystem.Controllers
{

public class AccountController : Controller


{
private BankingDBEntities db = new BankingDBEntities();

public ActionResult Register() => View();

[HttpPost]
public ActionResult Register(User user)
{
if (db.Users.Any(u => u.Email == user.Email))
{
ModelState.AddModelError("", "Email already exists.");
return View();
}
user.Balance = 0;
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Login","Account");
}

public ActionResult Login() => View();

[HttpPost]
public ActionResult Login(string email, string password)
{
var user = db.Users.FirstOrDefault(u => u.Email == email &&
u.Password == password);
if (user != null)
{
Session["UserId"] = user.UserId;
return RedirectToAction("Dashboard", "User");
}

var admin = db.Admins.FirstOrDefault(a => a.Email == email &&


a.Password == password);
if (admin != null)
{
Session["AdminId"] = admin.AdminId;
return RedirectToAction("Dashboard", "Admin");
}

ViewBag.Message = "Invalid credentials.";


return View();
}

public ActionResult Logout()


{
Session.Clear();
return RedirectToAction("Login");
}
}
}

ADMIN:

using BankingSystem.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BankingSystem.Controllers
{

public class AdminController : Controller


{
private BankingDBEntities db = new BankingDBEntities();

public ActionResult Dashboard()


{
return View(db.Users.ToList());
}
public ActionResult AddAmount() => View();

[HttpPost]
public ActionResult AddAmount(string email, decimal amount)
{
var user = db.Users.FirstOrDefault(u => u.Email == email);
if (user == null || amount <= 0)
{
ViewBag.Message = "Invalid user or amount.";
return View();
}

user.Balance += amount;
db.SaveChanges();
ViewBag.Message = "Amount added successfully.";
return View();
}

public ActionResult EditUser(int id)


{
var user = db.Users.Find(id);
return View(user);
}

[HttpPost]
public ActionResult EditUser(User updatedUser)
{
var user = db.Users.Find(updatedUser.UserId);
if (user != null)
{
user.FullName = updatedUser.FullName;
user.Email = updatedUser.Email;
user.BankName = updatedUser.BankName;
db.SaveChanges();
}
return RedirectToAction("Dashboard");
}

public ActionResult DeleteUser(int id)


{
var user = db.Users.Find(id);
db.Users.Remove(user);
db.SaveChanges();
return RedirectToAction("Dashboard");
}

public ActionResult PostAnnouncement() => View();

[HttpPost]
public ActionResult PostAnnouncement(Announcement announcement)
{
db.Announcements.Add(announcement);
db.SaveChanges();
ViewBag.Message = "Announcement posted.";
return View();
}
}

}
USER:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using BankingSystem.Models;

namespace BankingSystem.Controllers
{

public class UserController : Controller


{
private BankingDBEntities db = new BankingDBEntities();

public ActionResult Dashboard()


{

int userId = (int)Session["UserId"];


var user = db.Users.Find(userId);
return View(user);
}

public ActionResult Transfer() => View();

[HttpPost]
public ActionResult Transfer(string toEmail, decimal amount)
{
int fromUserId = (int)Session["UserId"];
var fromUser = db.Users.Find(fromUserId);
var toUser = db.Users.FirstOrDefault(u => u.Email == toEmail);

if (toUser == null || fromUser.Balance < amount || amount <= 0)


{
ViewBag.Message = "Invalid transfer.";
return View();
}

fromUser.Balance -= amount;
toUser.Balance += amount;

db.Transactions.Add(new Transaction
{
FromUserId = fromUserId,
ToUserId = toUser.UserId,
Amount = amount,
Type = fromUser.BankName == toUser.BankName ? "Internal" :
"External"
});

db.SaveChanges();
ViewBag.Message = "Transfer successful.";
return View();
}

public ActionResult PayBills() => View();

[HttpPost]
public ActionResult PayBills(string billType, decimal amount)
{
int userId = (int)Session["UserId"];
var user = db.Users.Find(userId);

if (user.Balance < amount || amount <= 0)


{
ViewBag.Message = "Insufficient balance or invalid amount.";
return View();
}

user.Balance -= amount;
db.Transactions.Add(new Transaction
{
FromUserId = userId,
ToUserId = null,
Amount = amount,
Type = "Bill Payment"
});

db.SaveChanges();
ViewBag.Message = "Bill paid successfully.";
return View();
}

public ActionResult Balance()


{
int userId = (int)Session["UserId"];
var user = db.Users.Find(userId);
ViewBag.Balance = user.Balance;
return View();
}

public ActionResult History()


{
int userId = (int)Session["UserId"];
var transactions = db.Transactions
.Where(t => t.FromUserId == userId || t.ToUserId == userId)
.OrderByDescending(t => t.Date)
.ToList();
return View(transactions);
}
}
}

VIEWS:

You might also like