How to run #Url.action written by string - c#

I am trying to show image from database with #Url.Action method. The html document is also in database and I render it with #html.Raw function.
The problem is when I render the html including #Url.Action method it just show the whole function shape in the source parameter. The code I tried is below.
private string ConvertImageSource(int articleID, string content // the html string)
{
var imageCount = // counting number of image;
for (int i = 0; i < imageCount; i++)
{
content = content.Replace($"<!{i + 1}>", $"#Url.Action('ShowImage','Articles',new{{articleID={ articleID },imageID={ imageID }}})");
}
return content;
}
public ActionResult ShowImage(int? articleID, int? imageID)
{
var imageData = Encoding.ASCII.GetBytes(// get image string from database);
return new FileStreamResult(new MemoryStream(imageData), "image/jpeg");
}
I would like to know how to make it works. Any idea?

You may use that for loop on a partial view.
Looks like..
#model MyContentModel
#for (int i = 0; i < model.ImageCount; i++){{
#Url.Action("ShowImage", "Articles", new {{ articleID ={ model.ArticleID },imageID ={ model.ImageID } }})}}

Thanks for the answer. I found the solution by myself.
Instead of #Url.Action function, I put url address and it works.
private string ConvertImageSource(int articleID, string content)
{
var imageCount = content.Split(new string[] { "img " }, StringSplitOptions.None).ToList().Count - 1;
for(int i = 0; i < imageCount; i++)
{
content = content.Replace($"<!{i + 1}>", $"/Articles/ShowImage?articleID={ articleID }&imageID={i + 1}");
}
return content;
}

Related

Add 2 parameters to Email Template Body

I have a email template and i have bind 1 parameter to it(this.OrderCode) and it's working .So now i need to bind another one.
Email Template Like Below,
string OrderTemplate="<p><%=this.OrderCode%></p><p><%=this.ReferredTo%></p>";
tempValues comes like below,
[0]this.OrderCode
[1]ODR5000
[2]this.ReferredTo
[3]Janez Smithson
Using below code i need to show both of above values.In here only shows 1st value only(ODR5000)
public string EmailTemplate(string OrderTemplate, params string[] tempValues)
{
string templatebody = string.Empty;
try
{
templatebody = OrderTemplate;
for (var i = 0; i < tempValues.Length; i++)
{
templatebody= templatebody.Replace("<%={0}%>".FormatWith(tempValues[i]), tempValues++);
}
}
catch (Exception ex)
{
throw ex;
Log4NetLogger.Log(ex);
}
return templatebody;
}
I have pretty similar function for that.
for (int i = 0; i < tempValues.Length; i++)
{
var pattern = string.Format(#"(\[{0}\])", i);
templatebody = Regex.Replace(templatebody, pattern, tempValues[i].ToString());
}

Using SimpleJSON C# help getting info

Do not say there is built in Unity Json or to download the Lindq for C# I am using SimpleJSON
I am trying to read the json file and add the elements to a list so I can call them easier. I cannot figure out how to add all of "Heads" values to list.
So I could possibly call
listname[index].key
listname[key].value
to return somthing where I can get example.("Small_Cube_Head":{"Colors":{"Default"})
I basically want to be able to call the "Small_Cube_Head" and all color values
JSON FILE
{
"Heads":{
"Large_Cube_Head":["Default","e97451"],
"Medium_Cube_Head":["Default","ffffff","76d7ea","e97451","5fa777","f4c430","d0ff14","0047ab","e32636","fc419a","720b98","ff8b00","000000","848482"],
"Small_Cube_Head":["Default"]
}
}
}
code
/**
* json: Returns the whole file as a String
**/
private void LoadJson()
{
using (StreamReader r = new StreamReader("Assets/JSON/PlayerPartsList.json"))
{
json = r.ReadToEnd();
//Debug.Log(json);
JSONNode node = JSON.Parse(json);
Debug.Log(node["Heads"].Count); //returns 3
for (int i = 0; i < node["Heads"].Count; i++) {
//headParts.Add(node["Heads"].);
//Debug.Log(node["Heads"][i].Value.ToString());
//Debug.Log(node["Heads"]["Small_Cube_Head"].Value);
}
}
}
Use Keys like an enumerator to get each head name, and then you can loop through the count of that headName as the index
KeyEnumerator headNameEnum = node["Heads"].Keys;
while (headNameEnum.MoveNext())
{
String headName = headNameEnum.Current().Value;
Debug.Log("headName: " + headName);
for (int i=0; i < node["Heads"][headName].Count; i++) {
String valueName = node["Heads"][headName][i].Value;
Debug.Log("valueName: " + valueName);
}
}

Are there any alternatives of ASP Panels to insert html from code?

I'm using an ASP panel as a placeholder to create things like menus that come from the database. For this I created a class with a function that returns a Panel.
Is there an alternative to this? I would like my code to be completly independed of the project. Maby some classic ASP function?
Code that creates the menu:
public static Panel createMenu(Panel panel)
{
List<menu> menuItems = menu.selectMenuitems();
panel.Controls.Add(new LiteralControl("<ul>"));
for (int i = 0; i < menuItems.Count; i++)
{
string menuPath = menuItems[i].virtualpath;
string menuName = menuItems[i].name;
panel.Controls.Add(new LiteralControl("<li>"));
// Get the full URL
string url = HttpContext.Current.Request.Url.AbsoluteUri;
// Get last part of the URL
string path = url.Split('/').Last().ToLower();
// If the url is the same as the menu-item, add class active.
if (path == menuPath || (path == "default.aspx" && i==0))
panel.Controls.Add(new LiteralControl("<a class='active' href='/" + menuPath + "'>"));
else
panel.Controls.Add(new LiteralControl("<a href='/" + menuPath + "'>"));
panel.Controls.Add(new LiteralControl(menuName));
panel.Controls.Add(new LiteralControl("</a>"));
panel.Controls.Add(new LiteralControl("</li>"));
}
panel.Controls.Add(new LiteralControl("</ul>"));
return panel;
}
Your menu structure appears to be something like this:
<ul>
<li><a class href>name</a></li>
</ul>
Why not just create a routine that outputs a string. You can pass the string over to a literal control to load the menu. Something like:
myLiteral.Text = createMenu();
This code is not tested, but hopefully gives you a start:
public static string createMenu()
{
List<menu> menuItems = menu.selectMenuitems();
var m = new StringBuilder();
m.AppendLine("<ul>");
for (int i = 0; i < menuItems.Count; i++)
{
string menuPath = menuItems[i].virtualpath;
string menuName = menuItems[i].name;
m.AppendLine("<li>");
// Get the full URL
string url = HttpContext.Current.Request.Url.AbsoluteUri;
// Get last part of the URL
string path = url.Split('/').Last().ToLower();
// If the url is the same as the menu-item, add class active.
m.AppendLine("<a " + setActiveClass(path, menuPath, i) + " href=\"/" + menuPath + "\">");
m.AppendLine(menuName);
m.AppendLine("</a>");
m.AppendLine("</li>");
}
m.AppendLine("</ul>");
return m.toString();
}
private static string setActiveClass(string path, string menuPath, int i) {
if (path.Equals(menuPath, StringComparison.OrdinalIgnoreCase) || (path.Equals("default.aspx", StringComparison.OrdinalIgnoreCase) && i==0)) {
return "class=\"active\"";
}
else {
return "";
}
}
You can also expand upon this to include sub-menus.
To be "independent" you could create the menu via Javascript/Jquery.
You can create a .ashx page or something like this that returns a JSON than you create the menu asynchronously. Your JSON should return a two keys structure like this
[{"menuName": "menu1","menuLink": "http://www.google.com"}, { "menuName": "menu2", "menuLink": "http://www.yahoo.com"}, { "menuName": "menu3", "menuLink": "http://www.pudim.com"}]';
Your JS/jQuery function would be like this
function createMenuAsync()
{
var menuContainer = $("#menuContainer");
var listRoot = $("<ul></ul>");
$.getJSON(callString, function (response) {
$.each(JSON.parse(response), function(key,value){
var listItem = $("<li></li>");
var itemLink = $("<a>" + value.menuName + "</a>").attr("href",value.MenuUrl);
itemLink.appendTo(listItem);
listItem.appendTo(listRoot);
})
});
listRoot.appendTo(menuContainer);
}
The code will be cleaner and will be lighter to your webserver, since the html tags elements will be created on client side instead of server side.
I create a fiddle with this code working
https://jsfiddle.net/h4ywwxm8/2/

C# Rotativa ActionAsPDF change text-direction right to left

i use Rotativa.ActionAsPdf to convert View to Pdf it works perfectly
but the problem how to change text-direction right to left?
here my code:
public ActionResult ExportPDF(ReportsModel RM)
{
string id = Session["Pat_id"].ToString();
string subPath = "~/Attachment/" + id;
string link;
bool exists = System.IO.Directory.Exists(Server.MapPath(subPath));
if (!exists)
System.IO.Directory.CreateDirectory(Server.MapPath(subPath));
return new Rotativa.ActionAsPdf("PhysicalExaminationSummaryToPDF", new { id = id })
{
FileName = "PhysicalExaminationSummary.pdf",
PageSize = Rotativa.Options.Size.Letter,
PageMargins = { Left = 0, Right = 0 }
};
}
Finnaly I solve it
should to add in view style direction:rtl
<style>
#status_quest {
direction:rtl;
}
</style>
when convert view to Pdf does not relate to CSS libraries

trouble comparing strings in wp7 application

Here is a sample of my code.
Here I recieve a string variable from another page.
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string newparameter = this.NavigationContext.QueryString["search"];
weareusingxml();
displayResults(newparameter);
}
private void displayResults(string search)
{
bool flag = false;
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("People.xml", FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Person>));
List<Person> data = (List<Person>)serializer.Deserialize(stream);
List<Result> results = new List<Result>();
for (int i = 0; i < data.Count; i++)
{
string temp1 = data[i].name.ToUpper();
string temp2 = "*" + search.ToUpper() + "*";
if (temp1 == temp2)
{
results.Add(new Result() {name = data[i].name, gender = data[i].gender, pronouciation = data[i].pronouciation, definition = data[i].definition, audio = data[i].audio });
flag = true;
}
}
this.listBox.ItemsSource = results;
}
catch
{
textBlock1.Text = "error loading page";
}
if(!flag)
{
textBlock1.Text = "no matching results";
}
}
Nothing is loaded into the list when the code is run, I just get the message "no matching results".
Looks like you are trying to do a contains search (my guess based on your addition of the * around the search string. You can remove the '*' and do a string.Contains match.
Try this.
string temp1 = data[i].name.ToUpper();
string temp2 = search.ToUpper()
if (temp1.Contains(temp2))
{
It looks like you are trying to check if one string contains another (ie substring match) and not if they are equal.
In C#, you do this like this:
haystack = "Applejuice box";
needle = "juice";
if (haystack.Contains(needle))
{
// Match
}
Or, in your case (and skip the * you added to the string temp2)
if (temp1.Contains(temp2))
{
// add them to the list
}
Have you checked to make sure data.Count > 0?

Categories

Resources