dont show help page in web api - webapi

I want to create help pages for ASP.NET Web API.
I created a new ASP.NET Web application project and select the Web API project template. It added Areas/HelpPage.
When I run the application, the home page contains a link to the API help page. From the home page, the relative path is /Help. It shows ValuesController action, but when I add another controller, the help page doesn't show that controller and any of its actions.
public class CalendarController : ApiController
{
private readonly string siteUrl = ConfigurationManager.AppSettings["SiteUrl"];
private readonly CalendarService calendarService;
public CalendarController()
{
calendarService = new CalendarService();
}
[HttpPost]
public async Task<ResponseModel<List<ApiCalendarViewModel>>> Paging(JObject param)
{
try
{
var startIndex = Convert.ToInt32(param["StartIndex"]);
var pageSize = Convert.ToInt32(param["PageSize"]);
var CalendarList = await calendarService.SelectAllAsync(startIndex, pageSize);
var list = CalendarList.Select(m => new ApiCalendarViewModel()
{
Author = m.Author,
Date = PersianDateTime.ToLongDateWithDayString(m.CreatedDate),
Excerpt = m.Excerpt,
Id = m.Id,
MainImage = siteUrl + m.Image,
Title = m.Title,
StartYear = m.StartYear,
EndYear = m.EndYear,
Semester = m.Semester.GetDisplayName()
}).ToList();
return new ResponseModel<List<ApiCalendarViewModel>>()
{
IsSuccess = true,
Data = list
};
}
catch (Exception e)
{
return new ResponseModel<List<ApiCalendarViewModel>>()
{
IsSuccess = false,
Message = e.Message
};
}
}
[HttpGet]
public async Task<ResponseModel<List<ApiCalendarViewModel>>> GetAll()
{
try
{
var CalendarList = await calendarService.SelectAllAsync();
var list = CalendarList.Select(m => new ApiCalendarViewModel()
{
Author = m.Author,
Date = PersianDateTime.ToLongDateWithDayString(m.CreatedDate),
Excerpt = m.Excerpt,
Id = m.Id,
MainImage = siteUrl + m.Image,
Title = m.Title,
StartYear = m.StartYear,
EndYear = m.EndYear,
Semester = m.Semester.GetDisplayName()
}).ToList();
return new ResponseModel<List<ApiCalendarViewModel>>()
{
IsSuccess = true,
Data = list
};
}
catch (Exception e)
{
return new ResponseModel<List<ApiCalendarViewModel>>()
{
IsSuccess = false,
Message = e.Message
};
}
}
}

Related

Why Restsharp request object won't be renewed in every call

This is my RestClientService :
public class RestClientService : IRestClientService
{
protected readonly RestClient _restClient;
protected readonly RestRequest _restRequest;
public RestClientService()
{
_restClient = new RestClient();
_restRequest = new RestRequest();
}
public async Task<MessageDTO> SendComment(Websites website, Comment comment, int postId)
{
if (await IsPostExist(postId,website))
{
_restClient.Options.BaseUrl = new Uri($"{website.Url}/wp-json/wp/v2/comments/");
_restRequest.Method = Method.Post;
_restRequest.RequestFormat = DataFormat.Json;
_restRequest.AddJsonBody(new
{
post = postId,
author_name = comment.Author,
content = comment.Body
});
var result = await _restClient.ExecuteAsync(_restRequest);
return new MessageDTO
{
Message = result.Content,
Status = result.StatusCode.ToString()
};
}
return new MessageDTO
{
Message = "Post Not Found",
Status = "404"
};
}
}
I have a list of comments and list of products that I iterate over them and call SendComment method from RestClientService class. The problem is in first time SendComment method called _restRequest object will be get JsonBody and everything is okay but next time this method calls in loop _restRequest object has old data and won't be renewed.
In DI Container I added (Transient) RestClientService
builder.Services.AddTransient<IRestClientService,RestClientService>();
Here is where I used SendComment method in another service.
public async Task<MessageDTO> CreateSendCommentJob(SendCommentConfiguration config)
{
var updatedConfig = await _sendCommentConfigurationRepository.Get(config.Id);
var ConfigDetails = JsonConvert.DeserializeObject<SendCommentConfigurationDetailsDTO>(updatedConfig.Configuration);
var mappedWebsite = _mapper.Map<Websites>(ConfigDetails.WebsiteInfo);
if (ConfigDetails.CommentType == "blog")
{
var comments = await _uCommentService.GetCommentsByGroupId(ConfigDetails.CommentGroupId);
var commentCount = 0;
for (int postCount = 0; postCount < ConfigDetails.ProductPerSendCount; postCount++)
{
var postId = ConfigDetails.Ids[postCount];
while (commentCount < ConfigDetails.CommentsPerProductCount)
{
var random = new Random();
var index = random.Next(comments.Count);
var result = await _restClientService.SendComment(mappedWebsite, comments[index], postId);
if (result.Status == "Created")
{
Console.WriteLine($"Comment Index ({index}) at Id ({postId}) submited successfuly...");
commentCount++;
}
else
{
Console.WriteLine($"{postId} - {result.Status} - {result.Message}");
}
}
ConfigDetails.Ids.Remove(postId);
commentCount = 0;
}
}
var newConfig = new SendCommentConfiguration
{
Id = config.Id,
Configuration = JsonConvert.SerializeObject(ConfigDetails)
};
await _sendCommentConfigurationRepository.Edit(newConfig);
return new MessageDTO
{
Status = "200",
Message = "Comments Successfuly Sent "
};
}
_restClientService.SendComment is called in a loop on the same service instance. As the request instance is a field of the service instance, the same request instance is reused for each call.
As each apple performs a distinct request, each request must use a distinct instance of RestRequest, like :
public class RestClientService : IRestClientService
{
public async Task<MessageDTO> SendComment(Websites website, Comment comment, int postId)
{
if (await IsPostExist(postId,website))
{
//Each call, new instances
var restClient = new RestClient();
var restRequest = new RestRequest();
restClient.Options.BaseUrl = new Uri($"{website.Url}/wp-json/wp/v2/comments/");
restRequest.Method = Method.Post;
restRequest.RequestFormat = DataFormat.Json;
restRequest.AddJsonBody(new
{
post = postId,
author_name = comment.Author,
content = comment.Body
});
var result = await restClient.ExecuteAsync(_restRequest);
return new MessageDTO
{
Message = result.Content,
Status = result.StatusCode.ToString()
};
}
return new MessageDTO
{
Message = "Post Not Found",
Status = "404"
};
}
}

SaveChangesAsync() getting stuck

I have problem and i think its a deadlock and i cant resolve the problem. I know there simular problem discuse but i need help. When i try to saveChange on productReposotory it stuck and dont execute the other code.
Here is my controller:
public IActionResult All(string type)
{
var viewModel = new AllFireplaceViewModel
{
Fireplaces =
this.fireplaceService.GetAllFireplaceAsync<IndexFireplaceViewModel>(type).Where(x => x.TypeOfChamber == type),
};
return this.View(viewModel);
}
My IFireplaceService:
using System.Collections.Generic;
using System.Threading.Tasks;
using KaminiCenter.Web.ViewModels.Fireplace;
public interface IFireplaceService
{
Task AddFireplaceAsync(FireplaceInputModel fireplaceInputModel);
IEnumerable<T> GetAllFireplaceAsync<T>(string type);
T GetByName<T>(string name);
}
And this is my implementation of the interface:
public async Task AddFireplaceAsync(FireplaceInputModel model)
{
var typeOfChamber = Enum.Parse<TypeOfChamber>(model.TypeOfChamber);
if (model.Power == null ||
model.Size == null ||
model.Chimney == null)
{
throw new ArgumentNullException("Cannot safe null or whitespace values!");
}
await this.productService.AddProductAsync(model.Name, model.Group);
var productId = this.productService.GetIdByNameAndGroup(model.Name, model.Group);
var groupId = this.groupService.FindByGroupName(model.Group).Id;
var fireplace = new Fireplace_chamber
{
Id = Guid.NewGuid().ToString(),
Power = model.Power,
Size = model.Size,
Chimney = model.Chimney,
Price = model.Price,
Description = model.Description,
ImagePath = model.ImagePath.ToString(),
TypeOfChamber = typeOfChamber,
ProductId = productId,
GroupId = groupId,
CreatedOn = DateTime.UtcNow,
ModifiedOn = DateTime.UtcNow,
};
await this.fireplaceRepository.AddAsync(fireplace);
await this.fireplaceRepository.SaveChangesAsync();
}
This is the productService.AddProductAsync:
public async Task AddProductAsync(string name, string groupName)
{
var group = this.groupService.FindByGroupName(groupName);
if (group == null)
{
await this.groupService.CreateAsync(groupName);
}
var product = new Product
{
// TO Check for Id Initializesion
Id = Guid.NewGuid().ToString(),
Name = name,
GroupId = group.Id,
CreatedOn = DateTime.UtcNow,
ModifiedOn = DateTime.UtcNow,
};
await this.productRepository.AddAsync(product);
await this.productRepository.SaveChangesAsync();
}
And my Add Action
public IActionResult Add()
{
var createFireplaceInputModel = new FireplaceInputModel();
return this.View(createFireplaceInputModel);
}

xamarin forms listview auto refresh

I'm new to Xamarin.Forms and I'm making a Listview that needs to update every time I insert new information in the database, so far I can display the info of my list and add it via a PHP file but I can't make it refresh automatically.
namespace Proyect
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Alarms : ContentPage
{
public Alarms ()
{
InitializeComponent();
AlarmsList.ItemTemplate = new DataTemplate(typeof(Cells.AlarmsCell)); //Template of the Alarms
this.LoadAlarms();
}
private async void LoadAlarms()
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("Http://192.168.0.13");
string url = string.Format("/Proyect/alarmscode.php?");
var response = await client.GetAsync(url);
var result = response.Content.ReadAsStringAsync().Result;
var jsonalarms = JsonConvert.DeserializeObject<ObservableCollection<GetAlarms>>(result);
AlarmsList.ItemsSource = jsonalarms;
}
catch (Exception e)
{
await DisplayAlert("ERROR", e + "", "OK");
return;
}
}
}
}
Can you try to keep the same ObservableCollection and update its content instead of setting a new ObservableCollection every time?
namespace Proyect
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Alarms : ContentPage
{
private ObservableCollection<GetAlarms> _itemsSource = null;
public Alarms()
{
InitializeComponent();
AlarmsList.ItemTemplate = new DataTemplate(typeof(Cells.AlarmsCell)); //Template of the Alarms
_itemsSource = new ObservableCollection<GetAlarms>();
AlarmsList.ItemsSource = _itemsSource;
this.LoadAlarms();
}
private async void LoadAlarms()
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("Http://192.168.0.13");
string url = string.Format("/Proyect/alarmscode.php?");
var response = await client.GetAsync(url);
var result = response.Content.ReadAsStringAsync().Result;
var jsonalarms = JsonConvert.DeserializeObject<ObservableCollection<GetAlarms>>(result);
_itemsSource.Clear();
foreach (var alarm in jsonalarms)
{
_itemsSource.Add(alarm);
}
}
catch (Exception e)
{
await DisplayAlert("ERROR", e + "", "OK");
return;
}
}
}
}
Device.StartTimer (new TimeSpan (0, 0, 10), () => {
// do something every 10 seconds
return true; // runs again, or false to stop
});

Paypal fail after first success testing asp mvc

I am trying to implement PayPal to my web app.
The very first time PayPal payment works fine!
But if I try second time, it fails. Can I only test once???
When PayPal succeeds I see this link:
https://localhost:44333/Paypal/PaymentWithPayPal?guid=94987&paymentId=PAY-1DM32358RW0519317LDPKCYY&token=EC-1G993722W11620224&PayerID=8QXDDJEKRZKZW
When PayPal fails I see this link:
https://localhost:44333/Paypal/PaymentWithPayPal?guid=52246&paymentId=PAY-9V465873R0219235GLDPKDNA&token=EC-1F105391KF572764B&PayerID=8QXDDJEKRZKZW
This is my PayPalController:
public class PayPalController : Controller
{
[Authorize]
// GET: PayPal
public ActionResult Index()
{
return View();
}
public ActionResult PaymentWithPaypal()
{
//getting the apiContext as earlier
APIContext apiContext = Configuration.GetAPIContext();
try
{
string payerId = Request.Params["PayerID"];
if (string.IsNullOrEmpty(payerId))
{
//this section will be executed first because PayerID doesn't exist
//it is returned by the create function call of the payment class
// Creating a payment
// baseURL is the url on which paypal sendsback the data.
// So we have provided URL of this controller only
string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority +
"/Paypal/PaymentWithPayPal?";
//guid we are generating for storing the paymentID received in session
//after calling the create function and it is used in the payment execution
var guid = Convert.ToString((new Random()).Next(100000));
//CreatePayment function gives us the payment approval url
//on which payer is redirected for paypal account payment
var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid);
//get links returned from paypal in response to Create function call
var links = createdPayment.links.GetEnumerator();
string paypalRedirectUrl = null;
while (links.MoveNext())
{
Links lnk = links.Current;
if (lnk.rel.ToLower().Trim().Equals("approval_url"))
{
//saving the payapalredirect URL to which user will be redirected for payment
paypalRedirectUrl = lnk.href;
}
}
// saving the paymentID in the key guid
Session.Add(guid, createdPayment.id);
return Redirect(paypalRedirectUrl);
}
else
{
// This section is executed when we have received all the payments parameters
// from the previous call to the function Create
// Executing a payment
var guid = Request.Params["guid"];
var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
if (executedPayment.state.ToLower() != "approved")
{
return View("FailureView");
}
}
}
catch (Exception ex)
{
Logger.Log("Error" + ex.Message);
return View("FailureView");
}
return View("SuccessView");
}
private PayPal.Api.Payment payment;
private Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId)
{
var paymentExecution = new PaymentExecution() { payer_id = payerId };
this.payment = new Payment() { id = paymentId };
return this.payment.Execute(apiContext, paymentExecution);
}
private Payment CreatePayment(APIContext apiContext, string redirectUrl)
{
var userId = User.Identity.GetUserId();
var userEmail = User.Identity.GetUserName();
//similar to credit card create itemlist and add item objects to it
var itemList = new ItemList() { items = new List<Item>() };
itemList.items.Add(new Item()
{
name = "Premium Monthly $99.00",
currency = "USD",
price = "99",
quantity = "1",
description = userEmail + " Pays Premium Monthly $99.00 on " + DateTime.Now.ToString("F")
});
var payer = new Payer() { payment_method = "paypal" };
// Configure Redirect Urls here with RedirectUrls object
var redirUrls = new RedirectUrls()
{
cancel_url = redirectUrl,
return_url = redirectUrl
};
// similar as we did for credit card, do here and create details object
var details = new Details()
{
subtotal = "99.00"
};
// similar as we did for credit card, do here and create amount object
var amount = new Amount()
{
currency = "USD",
total = "99.00", // Total must be equal to sum of shipping, tax and subtotal.
details = details
};
var transactionList = new List<Transaction>();
transactionList.Add(new Transaction()
{
description = userEmail + "Paid Premium Monthly $99.00 on " + DateTime.Now.ToString("F"),
invoice_number = "890918",
amount = amount,
item_list = itemList
});
this.payment = new Payment()
{
intent = "sale",
payer = payer,
transactions = transactionList,
redirect_urls = redirUrls
};
// Create a payment using a APIContext
return this.payment.Create(apiContext);
}
}
Please help!

Web API Typeless OData Service with OWIN self-hosting returns 406 Not Acceptable

I'm trying to set up a Web API Typeless OData Service with OWIN self-hosting... =)
But why not working? :~(
This is some code I have partially extracted from all kinds of examples out there...
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
var config = new HttpConfiguration();
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
appBuilder.UseWebApi(config);
}
}
public class Program
{
public static IEdmModel Model = GetEdmModel();
static void Main(string[] args)
{
using (WebApp.Start<Startup>("http://localhost:8080"))
{
Console.WriteLine("Running...");
Console.ReadLine();
}
}
public static IEdmModel GetEdmModel()
{
var model = new EdmModel();
// Create and add product entity type.
var product = new EdmEntityType("NS", "Product");
product.AddKeys(product.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));
product.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
product.AddStructuralProperty("Price", EdmPrimitiveTypeKind.Double);
model.AddElement(product);
// Create and add category entity type.
var category = new EdmEntityType("NS", "Category");
category.AddKeys(category.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));
category.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
model.AddElement(category);
// Set navigation from product to category.
var propertyInfo = new EdmNavigationPropertyInfo();
propertyInfo.Name = "Category";
propertyInfo.TargetMultiplicity = EdmMultiplicity.One;
propertyInfo.Target = category;
var productCategory = product.AddUnidirectionalNavigation(propertyInfo);
// Create and add entity container.
var container = new EdmEntityContainer("NS", "DefaultContainer");
model.AddElement(container);
// Create and add entity set for product and category.
var products = container.AddEntitySet("Products", product);
var categories = container.AddEntitySet("Categories", category);
products.AddNavigationTarget(productCategory, categories);
return model;
}
}
public class ProductsController : ODataController
{
private static readonly IQueryable<IEdmEntityObject> Products = Enumerable.Range(0, 10).Select(i =>
{
var productType = (IEdmEntityType)Program.Model.FindType("NS.Product");
var categoryType = (IEdmEntityTypeReference)productType.FindProperty("Category").Type;
var product = new EdmEntityObject(productType);
product.TrySetPropertyValue("Id", i);
product.TrySetPropertyValue("Name", "Product " + i);
product.TrySetPropertyValue("Price", i + 0.01);
var category = new EdmEntityObject(categoryType);
category.TrySetPropertyValue("Id", i % 5);
category.TrySetPropertyValue("Name", "Category " + (i % 5));
product.TrySetPropertyValue("Category", category);
return product;
}).AsQueryable();
public EdmEntityObjectCollection Get()
{
// Get Edm type from request.
var path = this.Request.GetODataPath();
var edmType = path.EdmType;
Contract.Assert(edmType.TypeKind == EdmTypeKind.Collection);
var collectionType = edmType as IEdmCollectionType;
var entityType = collectionType.ElementType.Definition as IEdmEntityType;
var model = Request.GetEdmModel();
var queryContext = new ODataQueryContext(model, entityType);
var queryOptions = new ODataQueryOptions(queryContext, Request);
// Apply the query option on the IQueryable here.
return new EdmEntityObjectCollection(new EdmCollectionTypeReference(collectionType, false), Products.ToList());
}
public IEdmEntityObject GetProduct(int key)
{
object id;
var product = Products.Single(p => HasId(p, key));
return product;
}
public IEdmEntityObject GetCategoryFromProduct(int key)
{
object id;
var product = Products.Single(p => HasId(p, key));
object category;
if (product.TryGetPropertyValue("Category", out category))
{
return (IEdmEntityObject)category;
}
return null;
}
public IEdmEntityObject Post(IEdmEntityObject entity)
{
// Get Edm type from request.
var path = Request.GetODataPath();
var edmType = path.EdmType;
Contract.Assert(edmType.TypeKind == EdmTypeKind.Collection);
var entityType = (edmType as IEdmCollectionType).ElementType.AsEntity();
// Do something with the entity object here.
return entity;
}
private bool HasId(IEdmEntityObject product, int key)
{
object id;
return product.TryGetPropertyValue("Id", out id) && (int)id == key;
}
}
The result I get is:
{StatusCode: 406, ReasonPhrase: 'Not Acceptable', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Date: Mon, 12 May 2014 18:08:25 GMT
Server: Microsoft-HTTPAPI/2.0
Content-Length: 0
}}
From running this:
var client = new HttpClient();
var response = client.GetAsync("http://localhost:8080/api/Products").Result;
If you are using OData V4, you need to make a change in your controller:
Old:
using System.Web.Http.OData;
New:
using System.Web.OData;

Resources