Need some help converting Js to C# - javascript

I need to convert this to c#, but I am not sure how to do it.
getParamsAsStr = function () {
var keys = Object.keys(_self.params ? _self.params : {});
keys.sort();
var response = "";
for (var i = 0 ; i < keys.length ; i++) {
response += _self.params[keys[i]];
}
return response;
}
(Basically, I would love to know what should I use instead of Object.keys)

This function iterates over some object's enumerable properties (Object.keys) and writes out the property values to a string - though without the keys and without any delimiters.
I don't know what _self.params refers to in this context as it isn't a JavaScript intrinsic nor have you provided its definition.
A direct translation to C# is not possible as C#/.NET do not use prototypes with enumerable properties, the closest analogue is to represent _self.params as a Dictionary<Object,String>:
public static String GetParamsAsStr(Dictionary<Object,String> p) {
if( p == null || p.Count == 0 ) return String.Empty;
StringBuilder sb = new StringBuilder();
foreach(Object key in p.Keys) sb.Append( p[key] );
return sb.ToString();
}

I am writing this as an answer to be able to place the whole thing...
This is the original JS code which sets the first parameter to make, later on, some API calls:
var Signer = function () {
this.apkId = getApkId();
this.apkSecret = getApkSecret();
this.servicio = "";
this.sessionToken = "";
this.timestamp = "";
this.requestId = "";
this.params = "";
var _self = this;
this.getParamsAsStr = function () {
var keys = Object.keys(_self.params ? _self.params : {});
keys.sort();
var response = "";
for (var i = 0 ; i < keys.length ; i++) {
response += _self.params[keys[i]];
}
return response;
}
this.getSignature = function () {
var baseString =
_self.apkSecret +
_self.servicio +
_self.sessionToken +
_self.timestamp +
_self.requestId +
_self.getParamsAsStr();
console.log("Signature pre hash:\n" + baseString);
baseString = baseString.toLowerCase();
return sha1(baseString);
}
}
And, so far, what I did in C# is the following:
public class Signer
{
public string appId = getApkId();
public string appSecret = getAppSecret();
public string servicio = "";
public string sessionToken = "";
public string timestamp = "";
public string requestId = "";
public string params = "";
//Here I have to write the getParamsAsStr()
private static string getApkId(){
string id = "xxxxxxxxxxxxxxxx";
return id;
}
private static string getAppSecret(){
string id = "xxxxxxxxxxxxxxxx";
return id;
}
}

Related

Save text from javascript variable to .txt file

I am trying this code, but can't get it to work, it says "The name "text" does not exist in the current context"
CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("for(var i = 0; i < elems1.length; i++){ var textt = elems1[i].innerText}");
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true))
{
outputFile.WriteLine(textt);
}
How can I make variable "textt" accessible?
Here is a full code:
private void button3_Click(object sender, EventArgs e)
{
CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("var elems1 = document.getElementsByClassName('question-text')");
CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("for(var i = 0; i < elems1.length; i++){var textt = elems1[i].innerText}");
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true))
{
outputFile.WriteLine(textt);
}
}
You might be looking for ContinueWith() which can be chained after ExecuteJavaScriptAsync().
In this example you need to use your JavaScript code as a function which returns anything (ex. textt). So I've created something like this:
var myScript = #"(function () {
var textt = "";
var elems1 = document.getElementsByClassName('question-text');
for(var i = 0; i < elems1.length; i++){
textt += elems1[i].innerText
}
return textt;
})();";
than I asynchronously evaluate it and catch the result which I am returning from that function:
var result = await CurBrowser
.GetMainFrame()
.EvaluateScriptAsync(myScript)
.ContinueWith(t => {
var result = t.Result; // your textt
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true)) {
outputFile.WriteLine(result);
}
});
this is just a suggestion of how it might work.

Getting C# Method With jQuery in asp.net

I am using the code below to display an uploaded picture in asp.net . The Image name is change to a unique name and args.get_fileName retrieves the original name of the file instead of the new unique name.
How can I retrieve the new unique name:
protected void FileUploadComplete(object sender, EventArgs e)
{
var date = DateTime.Now.ToString("yyyy-MM-dd-hh_mm_ss");
string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
AsyncFileUpload1.SaveAs("~/listingImages/" + date + filename);
}
Script:
function uploadStarted() {
$get("imgDisplay").style.display = "none";
}
function uploadComplete(sender, args) {
var imgDisplay = $get("imgDisplay");
imgDisplay.src = "images/loader.gif";
imgDisplay.style.cssText = "";
var img = new Image();
img.onload = function () {
imgDisplay.style.cssText = "height:100px;width:100px";
imgDisplay.src = img.src;
};
img.src = "/listingImages/" + args.get_fileName();
$('#bodyContent_Label1').html("/listingImages/" + args.get_fileName());
}
You should use password generating concept
private static string CreateRandomPassword(int passwordLength)
{
string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!#$?_-";
char[] chars = new char[passwordLength];
Random rd = new Random();
for (int i = 0; i < passwordLength; i++)
{
chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
}
return new string(chars);
}

Refresh page 5 times every half second, then append querystring to url using javascript or JQuery

I need to write some JavaScript or jQuery that refreshes a page, 5 times only, every 0.5 secs then once that is done append a querystring variable (?refreshed=yes) to the url using javascript or JQuery.
At present I have only been able to refresh once after 0.5 secs and append the ?refreshed=yes querystring. Can someone please point me in the right direction, many thanks in advance for any replies.
<script>
window.onload = function () {
if (!window.location.search) {
setTimeout("window.location+='?refreshed=yes';", 500);
}
}
</script>
C# code -
using LinkChex.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
namespace LinkChex.Base
{
public class WebSpider
{
const int LIMIT = 10;
string[] invalidTypes = { ".zip", ".doc", ".css", ".pdf", ".xls", ".txt", ".js", ".ico" };
public List<LinkModels> Links;
public bool foundMatch = false;
public bool IsRunning { get; set; }
public bool IsDone { get; set; }
public int totLinks { get; set; }
public WebSpider()
{
this.Links = new List<LinkModels>();
}
public void Execute(string url)
{
this.Links.Clear();
this.Links.Add(new LinkModels() { Status = HttpStatusCode.OK, NavigateUrl = url });
this.IsRunning = true;
WaitCallback item = delegate(object state) { this.FindLinks((UrlState)state); };
ThreadPool.QueueUserWorkItem(item, new UrlState() { Url = url, Level = 0 });
this.totLinks = Links.Count();
}
public void FindLinks(UrlState state)
{
try
{
string html = new WebClient().DownloadString(state.Url);
MatchCollection matches = Regex.Matches(html, "href[ ]*=[ ]*['|\"][^\"'\r\n]*['|\"]");
foreach (Match match in matches)
{
string value = match.Value;
value = Regex.Replace(value, "(href[ ]*=[ ]*')|(href[ ]*=[ ]*\")", string.Empty);
if (value.EndsWith("\"") || value.EndsWith("'"))
value = value.Remove(value.Length - 1, 1);
if (!Regex.Match(value, #"\((.*)\)").Success)
{
if (!value.Contains("http:"))
{
Uri baseUri = new Uri(state.Url);
Uri absoluteUri = new Uri(baseUri, value);
value = absoluteUri.ToString();
}
if (this.Links.Exists(x => x.NavigateUrl.Equals(value))) continue;
try
{
bool validLink = true;
foreach (string invalidType in invalidTypes)
{
string v = value.ToLower();
if (v.EndsWith(invalidType) || v.Contains(string.Format("{0}?", invalidType)))
{
validLink = false;
break;
}
}
if (validLink)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(value);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//add the OK link to the List object
//COMMENTED TO FILTER OUT OK LINKS
// this.Links.Add(new LinkModels() { Status = response.StatusCode, NavigateUrl = value });
if (response.StatusCode == HttpStatusCode.OK && state.Level < LIMIT)
{
WaitCallback item = delegate(object s) { FindLinks((UrlState)s); };
ThreadPool.QueueUserWorkItem(item, new UrlState() { Url = value, Level = state.Level + 1 });
}
}
}
catch
{
//add the ExpectationFailed link/s to the List object
this.Links.Add(new LinkModels(){ Status = HttpStatusCode.ExpectationFailed, NavigateUrl = value});
// this.IsDone = true;
}
}
}
}
catch
{
///
/// If downloading times out, just ignore...
///
}
}
}
}
controller class -
public WebSpider WebSpider
{
get { return (WebSpider)(Session["webSpider"] ?? (Session["webSpider"] = new WebSpider())); }
}
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult Details(string refreshed, int id = 0)
{
LinkModels lm = new LinkModels();
Domain domain = db.Domains.Find(id);
if (domain == null)
{
return HttpNotFound();
}
else
{
if (!this.WebSpider.IsRunning)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(domain.DomainDesc);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
this.WebSpider.Execute(domain.DomainDesc);
}
if (!this.WebSpider.IsRunning)
{
lm.SpiderRunning = this.WebSpider.IsRunning;
}
}
//remove duplicates from list object
var distinctList = this.WebSpider.Links.GroupBy(x => x.NavigateUrl)
.Select(g => g.First())
.ToList();
//only send email if page has been refreshed, NOT on initial load
if (Request["refreshed"] == "yes")
{
SendCertificate(domain.UserProfiles.UserName, domain.UserProfiles.UserEmail, domain.DomainDesc, distinctList);
}
return View(distinctList);
}
In query string add one more parameter like refresh=X and in your function parse this parameter.
The other option is for example use local storage for storing this data.
You can try something like:
var l = document.location,
m = l.search.match(/counter=(\d+)/),
counter = parseInt(m&&m[1]) || 0;
if (counter<5)
setTimeout(function() {
l.href = l.origin+l.pathname+"?counter="+(++counter);
},500);

Using ModelAndView object properties inside javascript

I am returning a list from my Controller as list to view and I am passing this list object to my javascript function like this
window.onload = function() {
showDirectory("$(S3DirectoryList)");
};
S3DirectoryList is the object that is returned from controller.
This is my model class
class Directory {
String folderName;
HashMap< String, String> objects;
List<Directory> dChild;
}
I want to use the folderName property of Directory in function.
Currently my javascript function is defined like this
function showDirectory( dirList) {
var markup="";
<c:forEach var="dir" items="dirList">
markup += ${dir.folderName} + "<br>";
</c:forEach>
document.getElementById("dispdir").innerHTML = markup;
}
I added some code to your Directory class. If you run it(I also added a Main method for testing purposes), you see it creates a list of directories and serializes this list as JSON. I added a constructor to make it easy to create some directories. I also added a getJSON method that serializes a directory. I added a getJSON(List directories) method to serialize a list of directories.
If you see to it this serialized list gets into your variable S3DirectoryList you can pass it to your javascript function as follows:
function showDirectory(dirList) {
var markup = "";
for(var i = 0; i < dirList.length; i++) {
markup += dirList[i].folderName + "<br />";
}
document.getElementById("dispdir").innerHTML = markup;
}
window.onload = function() {
showDirectory($(S3DirectoryList));
};
the Directory class:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class Directory{
String folderName;
HashMap<String, String> objects;
List<Directory> dChild;
public Directory(String folderName, String[] objects) {
this.folderName = folderName;
this.objects = new HashMap<String, String>();
for(int i = 0; i < objects.length; i = i + 2) {
this.objects.put(objects[i], objects[i + 1]);
}
this.dChild = new ArrayList<Directory>();
}
public void addChildDirectory(Directory childDirectory) {
if(this.dChild == null)
this.dChild = new ArrayList<Directory>();
this.dChild.add(childDirectory);
}
public String toJSON() {
StringBuilder b = new StringBuilder();
b.append("{");
b.append("'folderName': '").append(folderName == null ? "" : folderName).append("'");
b.append(",objects: {");
if(objects != null) {
Iterator<Map.Entry<String, String>> objectsIterator = objects.entrySet().iterator();
if(objectsIterator.hasNext()) {
Map.Entry<String, String> object = objectsIterator.next();
b.append("'").append(object.getKey()).append("': '").append(object.getValue()).append("'");
}
while (objectsIterator.hasNext()) {
Map.Entry<String, String> object = objectsIterator.next();
b.append(",'").append(object.getKey()).append("': '").append(object.getValue()).append("'");
}
}
b.append("}");
b.append(",'dChild': ");
b.append("[");
if(dChild != null) {
if(dChild.size() > 0)
b.append(dChild.get(0).toJSON());
for(int i = 1; i < dChild.size(); i++) {
b.append(",").append(dChild.get(i).toJSON());
}
}
b.append("]");
b.append("}");
return b.toString();
}
public static String getJSON(List<Directory> directories) {
StringBuilder b = new StringBuilder();
b.append("[");
if(directories.size() > 0)
b.append(directories.get(0).toJSON());
for(int i = 1; i < directories.size(); i++) {
b.append(",").append(directories.get(i).toJSON());
}
b.append("]");
return b.toString();
}
private static Directory generateDirectory(int seed) {
List<Directory> directories = new ArrayList<Directory>();
for(int i = 0; i < 5; i++) {
directories.add(
new Directory(
"folderName_" + seed + "_" + i,
new String[]{"k_" + seed + "_" + i + "_1", "v_" + seed + "_" + i + "_1", "k_" + seed + "_" + i + "_2", "k_" + seed + "_" + i + "_2"}));
}
Directory directory_root = directories.get(0);
Directory directory_1_0 = directories.get(1);
Directory directory_1_1 = directories.get(2);
Directory directory_1_0_0 = directories.get(3);
Directory directory_1_0_1 = directories.get(4);
directory_root.addChildDirectory(directory_1_0);
directory_root.addChildDirectory(directory_1_1);
directory_1_0.addChildDirectory(directory_1_0_0);
directory_1_0.addChildDirectory(directory_1_0_1);
return directory_root;
}
public static void main(String[] args) {
List<Directory> directories = new ArrayList<Directory>();
for(int i = 0; i < 2; i++) {
directories.add(generateDirectory(i));
}
System.out.println(toJSON(directories));
}
}

Trying to sort repeater rows with this jQuery

I am trying to sort repeater rows with this jquery . But I am not able to save sort items. Please help me . how can save sorting in database as well as in .aspx page?Thank you in advance
<script language="javascript" type="text/javascript">
$("#defaultList").sortable();
$(document).ready(function () {
$("#defaultList").sortable(
{
update: function (ev, ui) {
var result = $('#defaultList').sortable('toArray');
updateSequenceNumber(result);
}
}
);
});
function updateSequenceNumber(items) {
var originalIdAndSequenceNumber = '';
var index = 0;
for (i = 0; i <= items.length - 1; i++) {
if (items[i].length == 0)
continue;
var item = $('#' + items[i])[0];
originalIdAndSequenceNumber += item.attributes["originalId"].nodeValue + ":" + index.toString();
originalIdAndSequenceNumber += "|";
index = index + 1;
}
persistPositionUsingAjax(originalIdAndSequenceNumber);
}
function persistPositionUsingAjax(originalIdAndSequenceNumber) {
$.ajax(
{
type: "POST",
dataType: "text",
url: "AjaxService.asmx/UpdateSequenceNumber",
data: "s=" + originalIdAndSequenceNumber,
success: function (response) {
}
}
);
}
my ajax method:
[WebMethod]
public string UpdateSequenceNumber(string s)
{
s = s.TrimEnd('|');
string updateQuery = #"update dnn_Table_1 set SortId = {0}
where ImageId = {1}";
StringBuilder sb = new StringBuilder();
string[] originalIdAndSeqNumberArray = s.Split('|');
foreach (var originalIdAndSeqNumberCombined in originalIdAndSeqNumberArray)
{
var tempArray = originalIdAndSeqNumberCombined.Split(':');
int originalId = Convert.ToInt32(tempArray[0]);
int sequenceNumber = Convert.ToInt32(tempArray[1]);
sb.Append(String.Format(updateQuery, sequenceNumber, originalId));
sb.Append(System.Environment.NewLine);
}
UpdateInDatabase(sb.ToString());
return "Hello World";
}
private void UpdateInDatabase(string updateQuery)
{
SqlDataProvider sqd = new SqlDataProvider();
string ConnectionString = sqd.ConnectionString;
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand(updateQuery, conn);
command.CommandText = updateQuery;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
What status code does the ajax call return?
To me it looks like a 500. You are building an update statement that after a few iterations will look something like this
update dnn_Table_1 set SortId = 3 where ImageId = 2update dnn_Table_1 set SortId = 2 where ImageId = 4update dnn_Table_1 set SortId = 7 where ImageId = 6
That just won't work. Try eihter constructing the SQL update differently or move UpdateInDatabase into the foreach loop.
There might be other issues which I didn't spot, but this might be a starting point.
Hope that helps

Categories

Resources