Umbraco 6.1.6 Web API SSO Implementation - Final Page Accepting Token - c#

I've worked out all the problems with the WEB API implementation in Umbraco (Token & Member creation in an http post), the problem I'm having here is this final macro, I've created to drop in an Umbraco page, it will not collect the token and email from the querystring. I keep getting a System.Data.SqlClient.SqlException (expects the parameter '#token', which was not supplied) Am I not able to grab a querystring in Umbraco, or more specifically an Umbraco macro?
namespace ****.SSO
{
public partial class ****SSOMacro : System.Web.UI.UserControl,
umbraco.editorControls.userControlGrapper.IUsercontrolDataEditor
{
static Token token = new Token();
static string connStr = ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
try{
**string tmpToken = Request.QueryString["token"];
string tmpEmail = Request.QueryString["email"];
//Check If Token Still Exists
using (SqlConnection myConnection = new SqlConnection(connStr))
{
myConnection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM [DBTokenTable] WHERE tokens = #token and email = #email and valid = 'true'", myConnection);
command.Parameters.AddWithValue("#token", tmpToken);
command.Parameters.AddWithValue("#email", tmpEmail);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
token = new Token { token = reader["Tokens"].ToString(), email = reader["Email"].ToString(), valid = reader["Valid"].ToString() };
}
}
myConnection.Close();
}**
}
catch (Exception ex)
{
string error = ex.ToString();
//Log Any Form Cookies Out
FormsAuthentication.SignOut();
RawrLabel.Text = error;
//Response.Redirect(HttpUtility.UrlEncode("https://google.com/#q=" + error));
}
}
private string _umbval;
public object value
{
get { return _umbval; }
set { _umbval = value.ToString(); }
}

I was adding my macro onto a template page with Razor, so MVC didn't recognize the web forms Request.Querystring["value"] method. Instead just add the macro directly onto a content page with a Richtext editor.

Related

Is there a Method to read the Content of a Website?

I wanted to write a Program that reads an online Calendar, compares it with Names in a Database and uses this Data in some way. But if I use the WebClient, it reads the Source Code of the Website, not the Content. This is my Code:
using System;
using System.Diagnostics;
using System.Net;
using MySql.Data.MySqlClient;
namespace CalendarCrawler
{
class Program
{
static void KillTask(string Task)
{
Process[] Process = new Process[] { };
Process = Process.GetProcessesByName(Task);
foreach (Process Instance in Process)
{
Instance.Kill();
}
}
static String ReadContent(String Website)
{
WebClient web = new WebClient();
System.IO.Stream stream = web.OpenRead(Website);
using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
{
String text = reader.ReadToEnd();
return text;
}
}
static void Main(string[] args)
{
Console.WriteLine("Getting Connection ...");
var datasource = "localhost";//your server
var database = "database"; //your database name
var username = "username"; //username of server to connect
var password = "password"; //password
//your connection string
string connStr = $"Server={datasource};Database={database};Uid={username};Pwd={password}";
//create instanace of database connection
using (var conn = new MySqlConnection(connStr))
{
try
{
Console.WriteLine("Openning Connection ...");
//open connection
conn.Open();
Console.WriteLine("Connection successful!");
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
String Websitetext = ReadContent("http://www.esel.at/termine");
var stm = $"INSERT INTO content(Content) VALUES (#1);";
var cmd = new MySqlCommand(stm, conn);
cmd.Parameters.AddWithValue("#1", Websitetext);
cmd.ExecuteNonQuery();
Console.WriteLine(Websitetext);
KillTask("CalendarCrawler");
}
}
}
}
The Killtask Method is only to Clear it from the Background Processes, so there are no Problems with building a new Version.
I hope someone can help me.
There are effectively 2 different users of the web. People and computers. People like shiney things like buttons and tables (UI), computers prefer things like XML or JSON (API).
Your calendar web site has a UI, this is what you are currently seeing (both in a browser and when you 'download the code'). It probably has an API too and that is what you should be using in your program.
I've just had a quick look at esel.at and it doesn't appear to have a (public) API (but maybe that is because Google can't translate the page properly).

Getting wrong file path when generating file route in C# Console App

I'm trying to read in a SQL script in a C# console app. I'm having issues as the file route that it's generating always starts in the bin folder of the project.
public static void ApiResources(IConfiguration config, string testUrlExtension)
{
try
{
var azureDatabaseUrl = String.Format(config["SqlDatabase:BaseUrl"], $"test{testUrlExtension}");
SqlConnectionStringBuilder connBuilder = new SqlConnectionStringBuilder();
connBuilder.DataSource = azureDatabaseUrl;
connBuilder.UserID = config["SqlDatabase:ZupaKeyReleaseUserName"];
connBuilder.Password = config["SqlDatabase:ZupaKeyReleasePassword"];
connBuilder.InitialCatalog = "zupaauthentication";
using (SqlConnection connection = new SqlConnection(connBuilder.ConnectionString))
{
using (SqlCommand command = connection.CreateCommand())
{
connection.Open();
var GetLocalPathToProject = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Split("Zupa.ReleaseDeploymentAutoConfigure")[0];
var routeToApiResourseSqlScript = $"{GetLocalPathToProject}Zupa.ReleaseDeploymentAutoConfigure\\Zupa.ReleaseDeploymentAutoConfigure\\Sql\\Scripts\\";
var apiResourcesFileName = "AddApiResorces.sql";
var fullPathToSqlScript = $"{routeToApiResourseSqlScript}{apiResourcesFileName}";
command.CommandText = File.ReadAllText(fullPathToSqlScript);
command.ExecuteNonQuery();
connection.Close();
}
}
}
catch (SqlException e)
{
Console.WriteLine(e.InnerException);
}
}
The error I'm receiving is as follows:
Something went wrong try configuring the release again.
System.IO.IOException: The filename, directory name, or volume label syntax is incorrect. :
'C:\Zupa_Source_Code\Zupa.ReleaseDeploymentAutoConfigure\Zupa.ReleaseDeploymentAutoConfigure\bin\Debug\netcoreapp3.1\file:\C:\Zupa_Source_Code\Zupa.ReleaseDeploymentAutoConfigure\Zupa.ReleaseDeploymentAutoConfigure\Sql\Scripts\AddApiResorces.sql'
The correct path is being added to the end of the bin directory which is
file:\C:\Zupa_Source_Code\Zupa.ReleaseDeploymentAutoConfigure\Zupa.ReleaseDeploymentAutoConfigure\Sql\Scripts\AddApiResorces.sql
Change "CodeBase" in this line
var GetLocalPathToProject = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Split("Zupa.ReleaseDeploymentAutoConfigure")[0];
to be Location:
var GetLocalPathToProject = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).Split("Zupa.ReleaseDeploymentAutoConfigure")[0];

Transfer image capture photo from Phone gap to C# asp.net Web Service

Below is my j query function uploadPicOne()
$(function() {
var allVals = []; //for global check boxes
$(document).on("click", ".click-action-for-event", function(e) {
debugger;
//current i am calling this method for upload picture
uploadPicOne();
})
});
var uploadPicOne = function() {
navigator.camera.getPicture(updateProfilePicService_one, onFail, {
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
encodingType: navigator.camera.EncodingType.JPEG,
sourceType: navigator.camera.PictureSourceType.CAMERA
});
}
var updateProfilePicService_one = function(fileUri) {
SpinnerPlugin.activityStart("Loading...", { dimBackground: true });
var options = new FileUploadOptions();
options.fileKey = "image";
options.fileName = fileUri.substr(fileUri.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.params = {
"status": "B2",
"iTrainingId": $("#iTrainingId_currentprogramme").val(),
"session_date": $("#iTrainingDate_currentprogramme").val(),
};
options.headers = {
"X-Api-Key": localStorage.getItem("auth_key"),
};
options.chunkedMode = false;
var ft = new FileTransfer();
console.log(options);
ft.upload(fileUri, base_url + "uploadpic", win, fail, options);
}
Below is my webservice not sure its work for phone gap
[WebMethod]
public string uploadpic()
{
string msg = "";
using (SqlConnection con = new SqlConnection(strConn))
{
SqlCommand cmd = new SqlCommand("App_Service", con);
cmd.CommandType = CommandType.StoredProcedure;
try
{
var request = HttpContext.Current.Request;
IEnumerable<string> headers = request.Headers.GetValues("X-Api-Key");
var auth_key = headers.FirstOrDefault();
// HttpPostedFile file = HttpContext.Current.Request.Files["image"];
HttpPostedFile file = HttpContext.Current.Request.Files[0];
string saveFile = file.FileName;
file.SaveAs(Server.MapPath("/Trainer_Images/" + saveFile));
cmd.Parameters.AddWithValue("#Paravalue", "14");
cmd.Parameters.AddWithValue("#Value", saveFile);
cmd.Parameters.AddWithValue("#Value1", auth_key);
cmd.Parameters.AddWithValue("#Value2", "0");
cmd.Parameters.AddWithValue("#Value3", "0");
con.Open();
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
con.Dispose();
//Context.Response.Write(JSONResult);
//return d1.data;
/// msg = "File uploaded";
}
catch (Exception ex)
{
msg = "Could not upload file: " + ex.Message;
}
}
return msg;
}
I need to know my web service is correct or wrong. I am not able to run my webservice also, my requirement is send captured image file to my asp.net web-service and save to database, please help me to achieve my requirement or any suggestion or any examples related my need. The above jquery functions are working fine because the same app using into different application.
Today I have checked this code is not working through mobile showing loading after taking photo from mobile.
I think you are making asp.net web service (asmx).It needs ajax enabled to be called from JavaScript.
For your project i think you should use Asp.net mvc API
check this article.
https://www.c-sharpcorner.com/article/uploading-image-to-server-using-web-api-2-0/

Wrong JSON output from Web Api inside asp.net webforms

Am trying to use Web Api to output some json within an ASP.Net web forms web application.
Below is my get method:
public string Get()
{
String paramOne = "paramOneValue";
using (var conn = new SqlConnection(sqlConStr))
{
try
{
var command = new SqlCommand("getMyList", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#paramOne", paramOne);
conn.Open();
ArrayList result = new ArrayList();
var reader = command.ExecuteReader();
while (reader.Read())
{
result.Add(new
{
id = reader[0],
val= reader[1],
val1= reader[2]
});
}
return JsonConvert.SerializeObject(result);
}
catch (SqlException sxp)
{
string msg = Resource.fetchError + " " + sxp.Message;
return "error";
}
}
}
and below is the Response from firebug when the method is called within an aspx page:
"[{\"id\":1,\"val\":\"valFromDB\",\"val1\":\"valOneFromDB\"},{\"id\":2,\"val\":\"row2ValFromDB\",\"val1\":\"row2ValOneFromDB\"}]"
but the weird thing is under JSON tab individual characters are being returned as in below:
0 "["
1 "{"
2 """
3 "i"
4 "d"
Anything am missing?

Parsing excel .xls database into sql server database

I have asp.net mvc4 project, where have database with students, also have old database in .xls format and I need to migrate all values from old database into new one sql server database. In my mvc project I have membership controller which include method for Register new student. Also I'm write console application which parse .xls table and insert all values into my new database via Register method.
Console application:
static void Main(string[] args)
{
string con = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\MigrateExelSql\Include\TestDb.xlsx; Extended Properties=Excel 12.0;";
MembershipController mc = new MembershipController();
Student student = new Student();
student.Username = null;
student.Password = "password";
student.Email = null;
student.EntryYear = 2014;
student.PassportNumber = 0;
student.IsApproved = true;
student.PasswordFailuresSinceLastSuccess = 0;
student.IsLockedOut = false;
using(OleDbConnection connection = new OleDbConnection(con))
{
connection.Open();
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
using(OleDbDataReader dr = command.ExecuteReader())
{
while(dr.Read())
{
string row1Col0 = dr[0].ToString();
Console.WriteLine(row1Col0);
string row1Col1 = dr[1].ToString();
Console.WriteLine(row1Col1);
Console.WriteLine();
student.Username = row1Col0;
student.Email = row1Col1;
try
{
mc.Register(student);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Console.ReadKey();
}
Register method
public static MembershipCreateStatus Register(string Username, string Password, string Email, bool IsApproved, string FirstName, string LastName)
{
MembershipCreateStatus CreateStatus;
System.Web.Security.Membership.CreateUser(Username, Password, Email, null, null, IsApproved, null, out CreateStatus);
if (CreateStatus == MembershipCreateStatus.Success)
{
using (UniversityContext Context = new UniversityContext(ConfigurationManager.ConnectionStrings[0].ConnectionString))
{
Student User = Context.Students.FirstOrDefault(Usr => Usr.Username == Username);
User.FirstName = FirstName;
User.LastName = LastName;
Context.SaveChanges();
}
if (IsApproved)
{
FormsAuthentication.SetAuthCookie(Username, false);
}
}
return CreateStatus;
}
ActionResult POST
public ActionResult Register(Student student)
{
Register(student.Username, student.Password, student.Email, true, student.FirstName, student.LastName);
return RedirectToAction("Index", "Membership");
}
Everything work fine when I try to add students from web application, but when I try to add from my parsed database it was get the error on the next line
System.Web.Security.Membership.CreateUser(Username, Password, Email, null, null, IsApproved, null, out CreateStatus);
in my Register method, that invalidAnswer. I'm change null to "123456789", then next error will be invalidQuestion, then I'm also change from null to "123456789". And after this it's tell me that my invalidPassword. Also I'm added next line into my membership provider's line in my web.config requiresQuestionAndAnswer="false".
I have no idea why it's not working. Does anybody have any ideas?
Whenever I'm required to do anything like import data from spreadsheets like this simply write an Importer console app in my solution. I also use LINQ to CSV which you can get from Nuget and its a really useful tool to use.
It allows you to read in the data from your spreadsheet into the relevant class objects, and from there once you have validated each object you can simply create new objects in your Database using your Data Layer.
Since xls (not xlsx) files are basically text files in which contents are separated by usually a tab character (or maybe some certain spercial charchters) a better approach would be to read all the lines in the file and store them in a list.
Then you can split each element at the time you are inserting them in your database. This can be easily done using a foreach loop like:
foreach (var i in xlsList) {
String s [] = i.Split('\t').ToArray(); // refer to your file
for (int j = 0; j < s.lenght; j++) {
Your SQL statement in here
}
}

Categories