Generate a QR Code in ASP.NET C# without using a 3rd party provider - c#-4.0

I'm using ASP.NET identity 2 and one of the tutorials includes using a 3rd part provider to generate a QR Code for Google authenticator for two-factor authentication. However, I don't want to send that data to a 3rd party (which is what other solutions point to, like google, etc). I'm specifically looking for code to solve my issue.
I'd like either the server or the client to generate the QR Code. Anyone else have a good solution for doing this? Below is the line of code that generates the QR Code in the cshtml file. The #(Model.BarcodeURL) is the razor model attribute with the data for the QR Code.
<img src="http://qrcode.kaywa.com/img.php?s=4&d=#(Model.BarcodeUrl)" />

I was able to do this on the server using ZXing.Net and exposing an endpoint via a controller(MVC or Web API). The endpoint would receive data via query string and generate a QRCode on the server using ZXing.Net, then send it back as a stream. This allows one to show the code as an image.
<img src="http://localhost/barcode?d=#(Model.BarcodeUrl)" />
A MVC controller for the above src could look something like this.
....
using ZXing;
using ZXing.QrCode;
using ZXing.QrCode.Internal;
using System.Windows.Media.Imaging // for SaveJpeg extension
....
public class BarcodeController : Controller {
readonly IBarcodeWriter qrCodeWriter;
BarcodeController() {
qrCodeWriter = new BarcodeWriter {
Format = BarcodeFormat.QR_CODE,
Options = new QrCodeEncodingOptions {
Margin = 1,
Height = 600,
Width = 600,
ErrorCorrection = ErrorCorrectionLevel.Q,
},
};
}
public ActionResult Index(string d) {
var writeableBitmap = qrCodeWriter.Write(d);
var memoryStream = new MemoryStream();
writeableBitmap.SaveJpeg(memoryStream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 100);
return File(memoryStream.GetBuffer(), "image/jpeg");
}
}
Should be easy enough to do the same thing via an ApiController. You could also refactor out the code generation into a dedicated class if you want to separate concerns.

Related

Change culture for an ASP.NET Core 2 Razor page

I created an ASP.NET Core 2 projects with razor pages and I would like to give the opportunity to the visitor to select a language. The first problem that I had was to change the web application url so that ti will include the current language code. I solved this problem by adding the following code in ConfigureServices.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizeFolder("/Account/Manage");
options.Conventions.AuthorizePage("/Account/Logout");
options.Conventions.AddFolderRouteModelConvention("/", model =>
{
foreach (var selector in model.Selectors)
{
var attributeRouteModel = selector.AttributeRouteModel;
attributeRouteModel.Template = AttributeRouteModel.CombineTemplates("{language=el-GR}", attributeRouteModel.Template);
}
});
});
}
}
Now I could visit a page using the following URL:
http://domain/el-GR/MyPage
The last thing that I would like to do is to change the culture of each request. The best solution that I fount which I do not like is to put the following code in my page:
System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo((string)RouteData.Values["language"]);
System.Globalization.CultureInfo.CurrentUICulture = new System.Globalization.CultureInfo((string)RouteData.Values["language"]);
This is not nice because I will have to add these lies in every razor page that I will create in my project.
Is there another way to set the culture for all the requests of my web application?
Refer to this article: https://joonasw.net/view/aspnet-core-localization-deep-dive
There are a few methods, I use the RequestCultureProviders.
NuGet: Microsoft.AspNetCore.Localization
in my Startup.Configure method.
IList<CultureInfo> sc = new List<CultureInfo>();
sc.Add(new CultureInfo("en-US"));
sc.Add(new CultureInfo("zh-TW"));
var lo = new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-US"),
SupportedCultures = sc,
SupportedUICultures = sc
};
var cp = lo.RequestCultureProviders.OfType<CookieRequestCultureProvider>().First();
cp.CookieName = "UserCulture"; // Or whatever name that you like
app.UseRequestLocalization(lo);
Set your cookie "UserCulture" to "c=zh-TW|uic=zh-TW" once.
And it works magically.

How to I program a web-browser to perform a series of actions?

EDIT: I'm not looking for Facebook APIs! I'm simply using Facebook as an example. I intend to get my browser to perform actions on different websites that likely have no APIs.
Let's say I wish to create a program that will log into Facebook, lookup my friends list, visit each one of their profiles, extract the date + text of each post and write this to a file.
I have an idea how the algorithm should work. But I have absolutely no clue how to interface my code with the browser itself.
Now I'm a Java programmer, so I would very much imagine the pesudo code in Java would be to create a Browser Object then convert the current page's contents to HTML code so that the data can be parsed. I provided an example code below of what I think it ought to look like.
However is this the right way that I should be doing it? If it is, then where can I find a web browser object? Are there any parsers I can use to 'read' the content? How do I get it to execute javascript such as clicking on a 'Like' button?
Or are there other ways to do it? Is there a GUI version and then I can simply command the program to go to X/Y pixel position and click on something. Or is there a way to write the code directly inside my FireFox and run it from there?
I really have no clue how to go about doing this. Any help would be greatly appreciated! Thanks!
Browser browser = new Browser();
browser.goToUrl("http://facebook.com");
//Retrieve page in HTML format to parse
HtmlPage facebookCom = browser.toHtml();
//Set username & password
TextField username = facebookCom.getTextField("username");
TextField password = facebookCom.getTextField("password");
username.setText("user123");
password.setText("password123");
facebookCom.updateTextField("username", username);
facebookCom.updateTextField("password", password);
//Update HTML contents
browser.setHtml(facebookCom);
// Click the login button and wait for it to load
browser.getButton("login").click();
while (browser.isNotLoaded()) {
continue;
}
// Click the friends button and wait for it to load
browser.getButton("friends").click();
while (browser.isNotLoaded()) {
continue;
}
//Convert the current page (Friends List) into HTML code to parse
HtmlPage facebookFriends = browser.toHtml();
//Retrieve the data for each friend
ArrayList<XMLElement> friendList = facebookFriends.getXmlElementToArray("friend");
for (XMLElement friend : friendList) {
String id = friend.getId();
//Visit the friend's page
browser.goToUrl("http://facebook.com/" + id);
while (browser.isNotLoaded()) {
continue;
}
//Retrieve the data for each post
HtmlPage friendProfile = browser.toHtml();
ArrayList<XMLElement> friendPosts = friendProfile.getXmlElementToArray("post");
BufferedWriter writer = new BufferedWriter(new File("C:/Desktop/facebook/"+id));
//Write the date+text of every post to a text file
for (XMLElement post : friendPosts) {
String date = post.get("date");
String text = post.get("text");
String content = date + "\n" + text;
writer.append(content);
}
}
I think you are thinking about this the wrong way. You wouldn't really want to write a program to scrap the screen via the browser. It looks like you could take advantage of facebooks rest api and query for the data you are looking for. A link to get a users posts via rest api:
https://developers.facebook.com/docs/graph-api/reference/v2.6/user/feed
You could get their users id's from this endpoint:
https://developers.facebook.com/docs/graph-api/reference/friend-list/
Then plug the user ids into the first rest endpoint that was linked. Once you get your data coming back correctly via the rest api its fairly trivial to write that data out to a file.

CCavenue integration in liferay

Actually I have integrated CCAvenue JSP_Kit to my Lifreay portal 6.2. Till payment every thing is working properly that means after filling all the payment details and submitting no error is coming. But we are getting a response as null.
Below is the code of ReponseHandler.jsp.
encResp is coming null after payment or after cancel the request.
<%
String workingKey = "working key"; //32 Bit Alphanumeric Working Key should be entered here so that data can be decrypted.
String encResp= request.getParameter("encResp");
AesCryptUtil aesUtil=new AesCryptUtil(workingKey);
String decResp = aesUtil.decrypt(encResp);
StringTokenizer tokenizer = new StringTokenizer(decResp, "&");
Hashtable hs=new Hashtable();
String pair=null, pname=null, pvalue=null;
while (tokenizer.hasMoreTokens()) {
pair = (String)tokenizer.nextToken();
if(pair!=null) {
StringTokenizer strTok=new StringTokenizer(pair, "=");
pname=""; pvalue="";
if(strTok.hasMoreTokens()) {
pname=(String)strTok.nextToken();
if(strTok.hasMoreTokens())
pvalue=(String)strTok.nextToken();
hs.put(pname, pvalue);
}
}
}
%>
In the portal world you typically don't have access to the full and original HttpServletRequest. You can get access to it by calling
origRequest = PortalUtil.getOriginalHttpServletRequest(
PortalUtil.getHttpServletRequest());
This, of course, means that you're somewhat outside of the spec, however if you really need to communicate through servlet parameters, that might be your only option. I'd also recommend to add this code to a better testable/maintainable location - e.g. inside the Java Portlet class.
Here's the PortalUtil interface.

How to get Azure service pricing details programmatically?

Can anybody please tell me how can I programmatically get Azure service pricing details (pricing for Compute, Data Services , App Services, Network Services) from Azure website?
Does Azure provide the pricing details in JSON format?
Windows Azure does'not provide any such API as of today, although it is a much asked feature and hopefully they are working on it.
Check here:
http://feedback.windowsazure.com/forums/170030-billing/suggestions/1143971-billing-usage-api#comments
The only way for now could be to build your own data store with details mentioned here : http://azure.microsoft.com/en-us/pricing/calculator/
Unit wise price will be mentioned in the usage data csv, but unfortunately the only way for now is to download this csv for your subscription here: https://account.windowsazure.com/Subscriptions
Azure now provides API's to get usage and billing data. You can have a look at this blog which gives an overview of these API's and the feedback form here which contains links to some useful pages.
In summary use the following API's to get usage and billing data:
Resource usage
Resource ratecard
Not sure, if i am too late to answer.
I was looking for the same thing and stumble upon this post on stack overflow: Azure pricing calculator api. I was able to generate JSON string using this git hub repo: https://github.com/Azure-Samples/billing-dotnet-ratecard-api.
Hope this helps!
Late to the party but I found myself looking for this and nothing here got me what I wanted. Then I found this https://learn.microsoft.com/en-us/rest/api/cost-management/retail-prices/azure-retail-prices
It is pretty straight forward. Add the reference to the Json.NET .NET 4.0 to your project It shows up in your references as Newtonsoft.Json
//You will need to add these usings
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http;
private void btnGetRates_Click(object sender, EventArgs e)
{
string strUrl = "https://prices.azure.com/api/retail/prices?$filter=serviceName eq 'Virtual Machines' and skuName eq 'E64 v4' and reservationTerm eq '3 Years'";
string response = GetDataFromAPI(strUrl);
// Here is am turning the Json response into a datatable and then loading that into a DataGridView.
//You can use the Json response any way you wish
DataTable dt = Tabulate(response);
dgvAzureSKU.DataSource = null;
dgvAzureSKU.DataSource = dt;
}
public string GetDataFromAPI(string url)
{
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
var response = httpClient.GetStringAsync(new Uri(url)).Result;
return response;
}
}
public static DataTable Tabulate(string json)
{
var jsonLinq = JObject.Parse(json);
// Find the first array using Linq
var srcArray = jsonLinq.Descendants().Where(d => d is JArray).First();
var trgArray = new JArray();
foreach (JObject row in srcArray.Children<JObject>())
{
var cleanRow = new JObject();
foreach (JProperty column in row.Properties())
{
if (column.Value is JValue) // Only include JValue types
{
cleanRow.Add(column.Name, column.Value);
}
}
trgArray.Add(cleanRow);
}
return JsonConvert.DeserializeObject<DataTable>(trgArray.ToString()); //This is what loads the data into the table
}
You can find some examples for that here https://learn.microsoft.com/en-us/azure/billing/billing-usage-rate-card-overview. Azure provides invoice, usage and ratecard APIs which can help you to do things like:
Azure spend during the month
Set up alerts
Predict bill
Pre-consumption cost analysis

Orchard CMS: Do I have to add a new layer for each page when the specific content for each page is spread in different columns?

Lets say I want a different main image for each page, situated above the page title. Also, I need to place page specific images in the left bar, and page specific text in the right bar. In the right and left bars, I also want layer specific content.
I can't see how I can achieve this without creating a layer for each and every page in the site, but then I end up with a glut of layers that only serve one page which seems too complex.
What am I missing?
If there is a way of doing this using Content parts, it would be great if you can point me at tutorials, blogs, videos to help get my head round the issue.
NOTE:
Sitefinity does this sort of thing well, but I find Orchard much simpler for creating module, as well as the fact that it is MVC which I find much easier.
Orchard is free, I understand (and appreciate) that. Just hoping that as the product evolves this kind of thing will be easier?
In other words, I'm hoping for the best of all worlds...
There is a feature in the works for 1.5 to make that easier, but in the meantime, you can already get this to work quite easily with just a little bit of code. You should first add the fields that you need to your content type. Then, you are going to send them to top-level layout zones using placement. Out of the box, placement only targets local content zones, but this is what we can work around with a bit of code by Pete Hurst, a.k.a. randompete. Here's the code:
ZoneProxyBehavior.cs:
=====================
using System;
using System.Collections.Generic;
using System.Linq;
using ClaySharp;
using ClaySharp.Behaviors;
using Orchard.Environment.Extensions;
namespace Downplay.Origami.ZoneProxy.Shapes {
[OrchardFeature("Downplay.Origami.ZoneProxy")]
public class ZoneProxyBehavior : ClayBehavior {
public IDictionary<string, Func<dynamic>> Proxies { get; set; }
public ZoneProxyBehavior(IDictionary<string, Func<dynamic>> proxies) {
Proxies = proxies;
}
public override object GetMember(Func<object> proceed, object self, string name) {
if (name == "Zones") {
return ClayActivator.CreateInstance(new IClayBehavior[] {
new InterfaceProxyBehavior(),
new ZonesProxyBehavior(()=>proceed(), Proxies, self)
});
}
// Otherwise proceed to other behaviours, including the original ZoneHoldingBehavior
return proceed();
}
public class ZonesProxyBehavior : ClayBehavior {
private readonly Func<dynamic> _zonesActivator;
private readonly IDictionary<string, Func<dynamic>> _proxies;
private object _parent;
public ZonesProxyBehavior(Func<dynamic> zonesActivator, IDictionary<string, Func<dynamic>> proxies, object self) {
_zonesActivator = zonesActivator;
_proxies = proxies;
_parent = self;
}
public override object GetIndex(Func<object> proceed, object self, IEnumerable<object> keys) {
var keyList = keys.ToList();
var count = keyList.Count();
if (count == 1) {
// Here's the new bit
var key = System.Convert.ToString(keyList.Single());
// Check for the proxy symbol
if (key.Contains("#")) {
// Find the proxy!
var split = key.Split('#');
// Access the proxy shape
return _proxies[split[0]]()
// Find the right zone on it
.Zones[split[1]];
}
// Otherwise, defer to the ZonesBehavior activator, which we made available
// This will always return a ZoneOnDemandBehavior for the local shape
return _zonesActivator()[key];
}
return proceed();
}
public override object GetMember(Func<object> proceed, object self, string name) {
// This is rarely called (shape.Zones.ZoneName - normally you'd just use shape.ZoneName)
// But we can handle it easily also by deference to the ZonesBehavior activator
return _zonesActivator()[name];
}
}
}
}
And:
ZoneShapes.cs:
==============
using System;
using System.Collections.Generic;
using Orchard.DisplayManagement.Descriptors;
using Orchard;
using Orchard.Environment.Extensions;
namespace Downplay.Origami.ZoneProxy.Shapes {
[OrchardFeature("Downplay.Origami.ZoneProxy")]
public class ZoneShapes : IShapeTableProvider {
private readonly IWorkContextAccessor _workContextAccessor;
public ZoneShapes(IWorkContextAccessor workContextAccessor) {
_workContextAccessor = workContextAccessor;
}
public void Discover(ShapeTableBuilder builder) {
builder.Describe("Content")
.OnCreating(creating => creating.Behaviors.Add(
new ZoneProxyBehavior(
new Dictionary<string, Func<dynamic>> { { "Layout", () => _workContextAccessor.GetContext().Layout } })));
}
}
}
With this, you will be able to address top-level layout zones using Layout# in front of the zone name you want to address, for example Layout#BeforeContent:1.
ADDENDUM:
I have used Bertrand Le Roy's code (make that Pete Hurst's code) and created a module with it, then added 3 content parts that are all copies of the bodypart in Core/Common.
In the same module I have created a ContentType and added my three custom ContentParts to it, plus autoroute and bodypart and tags, etc, everything to make it just like the Orchard Pages ContentType, only with more Parts, each with their own shape.
I have called my ContentType a View.
So you can now create pages for your site using Views. You then use the ZoneProxy to shunt the custom ContentPart shapes (Parts_MainImage, Parts_RightContent, Parts_LeftContent) into whatever Zones I need them in. And job done.
Not quite Sitefinity, but as Bill would say, Good enough.
The reason you have to create your own ContentParts that copy BodyPart instead of just using a TextField, is that all TextFields have the same Shape, so if you use ZoneProxy to place them, they all end up in the same Zone. Ie, you build the custom ContentParts JUST so that you get the Shapes. Cos it is the shapes that you place with the ZoneProxy code.
Once I have tested this, I will upload it as a module onto the Orchard Gallery. It will be called Wingspan.Views.
I am away on holiday until 12th June 2012, so don't expect it before the end of the month.
But essentially, with Pete Hurst's code, that is how I have solved my problem.
EDIT:
I could have got the same results by just creating the three content parts (LeftContent, RightContent, MainImage, etc), or whatever content parts are needed, and then adding them to the Page content type.
That way, you only add what is needed.
However, there is some advantage in having a standard ContentType that can be just used out of the box.
Using placement (Placement.info file) you could use the MainImage content part for a footer, for example. Ie, the names should probably be part 1, part 2, etc.
None of this would be necessary if there was a way of giving the shape produced by the TextField a custom name. That way, you could add as may TextFields as you liked, and then place them using the ZoneProxy code. I'm not sure if this would be possible.

Resources