Make the Link NOT Editable asp.net c# Page - c#

I have a page there is a button that generates a Link like this.
private string GenerateLINK(string NameID)
{
string NameID= ds.Tables[0].Rows[0]["FName"] + " " + ds.Tables[0].Rows[0]["LName"];
string sQS = ID+ "|" + ClientName;
var xCrypto = new CryptoServer();
string Vector= null;
string sEncrypted = null;
xCrypto.Encrypt3DES(sQS, ref sEncrypted, ref Vector);
string sURL = sEncrypted + "#######" + Vector;
sURL = Server.UrlEncode(sURL);
sURL = "https://www.Page.aspx?s=" + sURL;
return sURL;
}
This then gets sent to a user who clicks on it and goes to a page.
Now the issue is I take the link like this and DCode it.
private void DecryptQuerystring()
{
var sQS = Request.QueryString["s"];
sQS = Server.UrlDecode(sQS);
var idelim = sQS.IndexOf("###X####", StringComparison.Ordinal);
var sIv = sQS.Substring(idelim + 8);
sQS = sQS.Substring(0, idelim);
var xCrypto = new ICECrypto.CryptoServer();
sQS = xCrypto.Decrypt3DES(sQS, sIv);
string sID = sQS.Substring(0, sQS.IndexOf("|"));
studentID = sID;
Name = sQS.Substring(sQS.IndexOf("|") + 1);
Welcome.InnerText = "Welcome " + sQS.Substring(sQS.IndexOf("|") + 1);
}
The Problem is when the User gets there and if he puts in any word in the link it breaks the whole page showing the Server Error. I want user to NOT to be able to Edit the Link insert any thing in it. Any clue? Thanks in advance!

This is funny but I am answering my own question maybe someone else could use it.
So where I am doing the Decryption of the QueryString() i put in the word
Try {
// Do the Decryption here
}
Catch(Exception ex) {
// if any thing goes wrong in that Try it will hit here and then i will show error 404
}

Related

Why can my WebClient not read a failed API call?

My code (intended for searching for steam market items using an API call) is supposed to read the response from an API call into my program and this works great, however, when the API call fails I want to display a separate error message letting the user know that something has gone wrong but currently it will simply crash the code.
An example of a successful API call is:
https://steamcommunity.com/market/priceoverview/?currency=2&appid=730&market_hash_name=Glock-18%20%7C%20Steel%20Disruption%20%28Minimal%20Wear%29
This results in the following;
{"success":true,"lowest_price":"\u00a31.39","volume":"22","median_price":"\u00a31.40"}
So far this works perfectly fine, the problem arises when an incorrect link is used, like this:
https://steamcommunity.com/market/priceoverview/?currency=2&appid=730&market_hash_name=this-skin-does-not-exist
This results in an error like so;
{"success":false}
I want to know when this happens so I can display a message to the user however in my code's current state it simply crashes when this is returned. Here's my current code:
webpage = "https://steamcommunity.com/market/priceoverview/?currency=2&appid=730&market_hash_name=" + Model.category + Model.weapon + " | " + Model.skin + " (" + Model.wear + ")";
System.Net.WebClient wc = new System.Net.WebClient();
byte[] raw = wc.DownloadData(webpage);
string webData = System.Text.Encoding.UTF8.GetString(raw);
if (webData.Substring(11, 1) == "t")
{
int lowestPos = webData.IndexOf("\"lowest_price\":\"");
int volumePos = webData.IndexOf("\",\"volume\":\"");
int medianPos = webData.IndexOf("\",\"median_price\":\"");
int endPos = webData.IndexOf("\"}");
Model.lowestPrice = webData.Substring(lowestPos + 16, volumePos - lowestPos - 16);
if (Model.lowestPrice.IndexOf("\\u00a3") != -1)
{
Model.lowestPrice = "£" + Model.lowestPrice.Substring(6);
}
Model.medianPrice = webData.Substring(medianPos + 18, endPos - medianPos - 18);
if (Model.medianPrice.IndexOf("\\u00a3") != -1)
{
Model.medianPrice = "£" + Model.medianPrice.Substring(6);
}
Model.volume = webData.Substring(volumePos + 12, medianPos - volumePos - 12);
}
else
{
Console.WriteLine("An error has occurred, please enter a correct skin");
}
The error occurs at byte[] raw = wc.DownloadData(webpage);
Any help would be appreciated :)
Webclient is deprecated and you should consider using HttpClient if possible. Webclient throws an exception. So you should wrap your code inside a try/catch block to catch the exception and react accordingly:
try
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] raw = wc.DownloadData(webpage);
string webData = System.Text.Encoding.UTF8.GetString(raw);
}
catch(System.Net.WebException e)
{
//handle the error here
}

Web Scraping of dynamic paginate value using C#

As i'm trying to web scrape a part from the website. Here is an image below.
as the pagination is checked in red box i need to extract value of last in the image above it is 151. So the pagination is dynamic which is hard to extract when i check using view page source in only <div class="jsx-46358917 pagination-wrapper text-center"></div> is shown as inside its value is missing as i understand it is dynamic but i need the last value from the pagination example 151.
Here is a code which i have done so far to web scrape it.
public void parseItem(HtmlDocument doc, string zipCode)
{
//Getting json data
if (doc.DocumentNode.LastChild.HasChildNodes)
{
var siteScripts = doc.DocumentNode.SelectSingleNode("//script[#id='__NEXT_DATA__']").InnerText;
var result = JsonConvert.DeserializeObject<RealtorModel>(siteScripts);
if (result != null)
{
foreach (var realtor in result.Props.CriteriaData.SrpShell.LoadedData.SearchResults.HomeSearch.Results)
{
string propertyId = "M" + realtor.PropertyId;
string address = realtor.Location.Address.Line + ", " + realtor.Location.Address.City + ", " + realtor.Location.Address.StateCode + " " + realtor.Location.Address.PostalCode;
string listingURL = hostName + "/realestateandhomes-detail/" + realtor.Permalink;
var url = realtor.PrimaryPhoto;
listings.Add(new Listings { PropertyID = propertyId, Address = address, Price = realtor.ListPrice, ImageURL = realtor.PrimaryPhoto.Href.AbsoluteUri, ListingURL = listingURL });
}
}
pageNumber = pageNumber + 1;
string nextUrl = "https://www.realtor.com/realestateandhomes-search/" + zipCode + "/type-single-family-home" + "/pg-" + pageNumber;
AddTask(nextUrl, this.parseItem, zipCode);
}
else
{
System.Threading.Thread.Sleep(60000);
string nextUrl = "https://www.realtor.com/realestateandhomes-search/" + zipCode + "/type-single-family-home" + "/pg-" + pageNumber;
AddTask(nextUrl, this.parseItem, zipCode);
}
}
As i get the complete page through scraping only thing is the last value of the paginate which i cannot extract due to its dynamic nature. How can i achieve to do so any hint would be helpful.

php-cgi POST request turns into GET request for no reason

I'm developping a windows web server in php and I want to use php-cgi.
It works well but I'm having problems with GET and POST request. When I set enviroment variable "REQUEST_METHOD" to "POST", I don't get anything in the $_POST variable but I get the content in $_GET :/ It doesn't make ANY sense...
Here is my code:
Process php = new Process();
php.StartInfo.FileName = "C:/PHP-7.1/php-cgi.exe";
php.StartInfo.RedirectStandardOutput = true;
php.StartInfo.UseShellExecute = false;
php.StartInfo.EnvironmentVariables["GATEWAY_INTERFACE"] = "CGI/1.1";
php.StartInfo.EnvironmentVariables["SCRIPT_FILENAME"] = page;
php.StartInfo.EnvironmentVariables["REQUEST_METHOD"] = "POST";
php.StartInfo.EnvironmentVariables["REDIRECT_STATUS"] = "true";
php.StartInfo.EnvironmentVariables["SERVER_PROTOCOL"] = "HTTP/1.1";
php.StartInfo.EnvironmentVariables["SERVER_SOFTWARE"] = ServerVersion;
php.StartInfo.EnvironmentVariables["REMOTE_HOST"] = "127.0.0.1";
//php.StartInfo.EnvironmentVariables["CONTENT_LENGTH"] = "3"; // Causes crash
php.StartInfo.EnvironmentVariables["HTTP_ACCEPT"] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
php.StartInfo.EnvironmentVariables["CONTENT_TYPE"] = "text/html";
String QueryString = "";
if (request.GET_Variables.Count() > 0)
{
int i = 0;
foreach (String variable in request.GET_Variables)
{
QueryString += variable + "=" + request.GET_Values[i];
i++;
if (i != request.GET_Variables.Count())
{
QueryString += "&";
}
}
}
php.StartInfo.EnvironmentVariables["QUERY_STRING"] = QueryString;
php.StartInfo.Arguments = "-f \"" + page + "\"";
Console.WriteLine("php-cgi.exe " + php.StartInfo.Arguments); // Debug
php.Start();
For example, If:
QUERY_STRING="fox=brown&dog=lazy"
The var_dump(); will look like this:
GET: array(2) { ["fox"]=> string(5) "brown" ["dog"]=> string(4) "lazy" }
POST: array(0) { }
I hope someone can help me, have a nice day !

Youtube Gdata Users Feed Stop Working

I have one application which is gathering the videos from youtube users.
since 3 days it is stopped and not gatehring videos and the only one video in listview is showing the youtube url: "https://www.youtube.com/devicesupport"
I have read that url but still not understand why it is not working. If someone has same issue I will appreciate to help me out.
My code:
private void Get_Video_Of_Searched_User()
{
using (new CWaitCursor())
{
int TotalVideoFound = 0;
string VideoID = string.Empty;
string YouTube_User = this.Txt_Youtube_UserName.Text;
int StartIndex = (Current_Page * 50) + 1;
YouTubeService ytsService = new YouTubeService(strAppName, strKey);
Uri urlEntryUrl = default(Uri);
urlEntryUrl = new Uri("https://gdata.youtube.com/feeds/api/users/" + YouTube_User + "/uploads?&max-results=50&start-index=" + StartIndex.ToString() + "");
FeedQuery fqResults = new FeedQuery();
fqResults.Uri = urlEntryUrl;
Feed<Video> vidFeed = new Feed<Video>(ytsService, fqResults);
try
{
TotalVideoFound = vidFeed.TotalResults;
}
catch
{
MessageBox.Show("Incorrect Username.");
return;
}
if (StartIndex == 1)
Lbl_TotalVideos.Text = "Total Videos: (" + TotalVideoFound.ToString() + ")";
Enable_Disable_Next_And_Previous_Buttons(TotalVideoFound);
SortedDictionary<string, string> ListViewItems = new SortedDictionary<string, string>();
Dict_User_Links_With_Title.Clear();
foreach (Video vidEntry in vidFeed.Entries)
{
if (ListViewItems.ContainsKey(vidEntry.Title) == true) continue;
ListViewItems.Add(vidEntry.Title, vidEntry.ViewCount.ToString());
VideoID = vidEntry.Id;
if (!Dict_User_Links_With_Title.ContainsKey(VideoID.Substring(VideoID.LastIndexOf(":") + 1)))
Dict_User_Links_With_Title.Add(VideoID.Substring(VideoID.LastIndexOf(":") + 1), vidEntry.Title);
}
ListView_User_Video_Links.Items.Clear();
string[] MyListItems = new string[2];
foreach (KeyValuePair<string, string> entry in ListViewItems)
{
MyListItems[0] = entry.Key;
MyListItems[1] = entry.Value;
ListView_User_Video_Links.Items.Add(new ListViewItem(MyListItems));
}
string TotalViews = Get_Youtube_User_Total_Views(YouTube_User);
this.Total_Views_For_User.Text = "Total Views: (" + TotalViews + ")";
}
}
Version 3 of the YouTube Data API has concrete quota numbers listed in the Google API Console where you register for your API Key. You can use 30,000 units/second/user and 50,000,000 per day.
If you hit the limits, Google will stop returning results until your quota is reset.

response redirect makes session_end in global asax

I am getting frustrated due to the session become null.When I click on save button I save the data to DB from code behind and if this successfully I am redirecting the user to the main projects page,using syntax:
Response.Redirect("~/Admin/Projects.aspx?i=esc&prjName=abc",'false');
but its make my session null.Its goes to Globex.asax page ang executes the Session_End and make all session null.
I even tried Server.Transfer but by this the browser url remains same and client doesn't want this.Even some where I read that the Server.Execute is also used to redirect but it is showing some wrong results.
can I use the Response.Redirect without this session null problem ??
(In this page I am creating the text file to store some long description and if this is successful then I am redirecting to the another page.)
Update::
here is my code for button click
protected void lnkbtnAddDescription_Click(object sender, EventArgs e)
{
try
{
if ((!hidProjId.Value.ToString().Equals("") || !hidEditProjId.Value.ToString().Equals("")) && !txtDescription.Value.ToString().Equals(""))
{
//ProjectDescription
int projId = 0;
if (!hidIsEdit.Value.ToString().Equals(""))
{
projId = Convert.ToInt32(hidEditProjId.Value.ToString());
}
else
{
projId = Convert.ToInt32(hidProjId.Value.ToString());
}
ProjectM proj = new ProjectM();
proj.LoadByKey(projId);
string prj = proj.ProjectName.ToString().Replace(" ", "-");
string strDirectoryPath = Server.MapPath("~/ProjectDescription/") + proj.ProjectId + "-" + prj;
if (!Directory.Exists(strDirectoryPath))
{
Directory.CreateDirectory(strDirectoryPath);
string filePath = strDirectoryPath + "/" + proj.ProjectId + "-" + prj + ".txt";
string strDescription = txtDescription.Value.ToString().Replace("<br />", "<p>");
createTextFile(filePath, strDescription);
string dbDirectoryPath = "~/ProjectDescription/" + proj.ProjectId + "-" + prj + "/" + proj.ProjectId + "-" + prj + ".txt";
proj.Description = dbDirectoryPath.ToString();
proj.IsNew = false;
proj.Save();
if (!hidIsEdit.Value.ToString().Equals(""))
{
//Server.Execute("~/SuperAdmin/Projects.aspx?i=esc&prjName=" + proj.ProjectName.ToString() + "",false);
Session["dsProj"] = null;
Session["editProjId"] = null;
Session["fname"] = hidFname.Value.ToString();
Session["UserId"] = hidUserId.Value.ToString();
Session["role"] = hidRole.Value.ToString();
Response.Redirect("~/SuperAdmin/Projects.aspx?i=esc&prjName=" + proj.ProjectName.ToString());
}
else
{
//Server.Execute("~/SuperAdmin/Projects.aspx?i=sc&prjName=" + proj.ProjectName.ToString() + "",false);
Session["dsProj"] = null;
Session["editProjId"] = null;
Session["fname"] = hidFname.Value.ToString();
Session["UserId"] = hidUserId.Value.ToString();
Session["role"] = hidRole.Value.ToString();
Response.Redirect("~/SuperAdmin/Projects.aspx?i=sc&prjName=" + proj.ProjectName.ToString());
}
}
else
{
Directory.Delete(strDirectoryPath, true);
Directory.CreateDirectory(strDirectoryPath);
string fileName = proj.ProjectName.ToString().Replace(" ", "-");
string filePath = strDirectoryPath + "/" + proj.ProjectId + "-" + fileName + ".txt";
string strDescription = txtDescription.Value.ToString().Replace("<br>", "<p>");
createTextFile(filePath, strDescription);
string dbDirectoryPath = "~/ProjectDescription/" + proj.ProjectId + "-" + proj.ProjectName.ToString() + "/" + proj.ProjectId + "-" + proj.ProjectName.ToString() + ".txt";
proj.Description = dbDirectoryPath.ToString();
proj.IsNew = false;
proj.Save();
if (!hidIsEdit.Value.ToString().Equals(""))
{
//Server.Execute("~/SuperAdmin/Projects.aspx?i=esc&prjName=" + proj.ProjectName.ToString() + "", false);
Session["dsProj"] = null;
Session["editProjId"] = null;
Session["fname"] = hidFname.Value.ToString();
Session["UserId"] = hidUserId.Value.ToString();
Session["role"] = hidRole.Value.ToString();
Response.Redirect("~/SuperAdmin/Projects.aspx?i=esc&prjName=" + proj.ProjectName.ToString());
}
else
{
//Server.Execute("~/SuperAdmin/Projects.aspx?i=sc&prjName=" + proj.ProjectName.ToString() + "", false);
Session["dsProj"] = null;
Session["editProjId"] = null;
Session["fname"] = hidFname.Value.ToString();
Session["UserId"] = hidUserId.Value.ToString();
Session["role"] = hidRole.Value.ToString();
Response.Redirect("~/SuperAdmin/Projects.aspx?i=sc&prjName=" + proj.ProjectName.ToString());
}
}
}
}
catch (Exception)
{
}
}
private void createTextFile(string filePath, string strDescription)
{
try
{
StreamWriter w = File.CreateText(filePath);
w.WriteLine(strDescription);
w.Flush();
w.Close();
}
catch (Exception ex)
{
}
}
Before you redirect to the next page,
assign the existing session value in the button click event also.
This would solve the problem.
hope this will be helpful to you,
ASP.NET Session becomes null after postback on local
This think your problem is related to some kind of permission denial, which is nulling your session.
There must be a problem in creating or saving the text file.
This may be making Session_End call so you are getting all values null.
Folder delete, move, rename causes Session end and long refresh
http://www.telerik.com/community/forums/aspnet-ajax/file-explorer/folder-delete-move-rename-causes-session-end-and-long-refresh.aspx#1365780

Categories