How can I use ext:CheckColumn in gridpanel with Linq2Sql? - linq-to-sql

I just want to bind the data in a gridpanel which uses CheckColumn. The checkboxes need to be checked if 'true' and unchecked if 'false'. I don't know how to do this. I need your help. Please I need a simple example.

U dont need to do any special thing.just decribe the colum as a CheckColumn and bind data ,here is the simple example
<ext:GridPanel runat="server" ID="grd" Height="300" Layout="FitLayout">
<Store>
<ext:Store runat="server">
<Model>
<ext:Model runat="server">
<Fields>
<ext:ModelField Name="data0"></ext:ModelField>
<ext:ModelField Name="data1"></ext:ModelField>
<ext:ModelField Name="data2"></ext:ModelField>
</Fields>
</ext:Model>
</Model>
</ext:Store>
</Store>
<ColumnModel>
<Columns>
<ext:Column ID="Column1" runat="server" DataIndex="data0" Text="data0"></ext:Column>
<ext:Column ID="Column2" runat="server" DataIndex="data1" Text="data1"></ext:Column>
<ext:CheckColumn runat="server" DataIndex="data2" Text="data2"></ext:CheckColumn>
</Columns>
</ColumnModel>
</ext:GridPanel>
and code behind;
public partial class TestCase : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//grd.GetStore().DataSource = GetData();
//grd.DataBind(); //OR with linq,
var Linqdata = from dt in GetData() select dt;
grd.GetStore().DataSource = Linqdata;
grd.DataBind();
}
private object[] GetData()
{
return new object[] {
new object[] { "test1", "test1", true },
new object[] { "test2", "test2", false },
new object[] { "test3", "test3", false } };
}
}

Related

I want to make sure my code meet the standard and security

Am new to ASP.NET and i just developed a simple online examination portal for learning.
I used ADO.NET,MySql and developed in VS 2010.
I have a login page in which user can login and register page for new user.After successful login user is redirected to the question page and i fetch the first question from database.
I populated the question in label and options in Radio Button list.User can select one option and click next button.
In the click event of next button i calculate the marks.
I store all values in session only.When user click next of last question that is 4 user is redirected to result page and print the marks.
This is my code
public partial class Questions : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
Response.Cache.SetNoStore();
if (!IsPostBack)
{
renderQuestions(1);
Session["buttonIndex"] = 1;
Session["Marks"] = 0;
}
}
public void renderQuestions(int index)
{
MySqlConnection con = null;
string conString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
string qry = "SELECT * FROM QUESTIONS WHERE QUESTION_ID="+index+"";
try
{
using (con = new MySqlConnection(conString))
{
con.Open();
using (MySqlCommand cmd = new MySqlCommand(qry, con))
{
using (MySqlDataAdapter ada = new MySqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
ada.Fill(dt);
if (dt.Rows.Count > 0)
{
clsQuestion ques = new clsQuestion();
ques.QuestionId = Convert.ToInt32(dt.Rows[0][0]);
ques.Question = Convert.ToString(dt.Rows[0][1]);
ques.Option1 = Convert.ToString(dt.Rows[0][2]);
ques.Option2 = Convert.ToString(dt.Rows[0][3]);
ques.Option3 = Convert.ToString(dt.Rows[0][4]);
ques.Option4 = Convert.ToString(dt.Rows[0][5]);
ques.Answer = Convert.ToInt32(dt.Rows[0][6]);
renderQuesAndAnswers(ques);
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
public void renderQuesAndAnswers(clsQuestion quest)
{
lblQuestion.Text = quest.Question;
RadioButtonList1.Items.Clear();
RadioButtonList1.Items.Add(quest.Option1);
RadioButtonList1.Items.Add(quest.Option2);
RadioButtonList1.Items.Add(quest.Option3);
RadioButtonList1.Items.Add(quest.Option4);
Session["QuestionNumber"] = quest.QuestionId ;
Session["Answer"] = quest.Answer;
}
public class clsQuestion
{
private int questionId;
private string question;
private string option1;
private string option2;
private string option3;
private string option4;
private int answer;
public int QuestionId
{
get { return questionId; }
set { questionId = value; }
}
public string Question
{
get { return question; }
set { question = value; }
}
public string Option1
{
get { return option1; }
set { option1 = value; }
}
public string Option2
{
get { return option2; }
set { option2 = value; }
}
public string Option3
{
get { return option3; }
set { option3 = value; }
}
public string Option4
{
get { return option4; }
set { option4 = value; }
}
public int Answer
{
get { return answer; }
set { answer = value; }
}
}
protected void option1_CheckedChanged(object sender, EventArgs e)
{
if (Convert.ToInt32 (Session["Answer"]) == 1)
{
int marks=Convert.ToInt32 (Session["Marks"]);
marks++;
Session["Marks"] = marks;
}
}
protected void option2_CheckedChanged(object sender, EventArgs e)
{
if (Convert.ToInt32(Session["Answer"]) == 2)
{
int marks = Convert.ToInt32(Session["Marks"]);
marks++;
Session["Marks"] = marks;
}
}
protected void option3_CheckedChanged(object sender, EventArgs e)
{
if (Convert.ToInt32(Session["Answer"]) == 3)
{
int marks = Convert.ToInt32(Session["Marks"]);
marks++;
Session["Marks"] = marks;
}
}
protected void option4_CheckedChanged(object sender, EventArgs e)
{
if (Convert.ToInt32(Session["Answer"]) == 4)
{
}
}
protected void btnNext_Click(object sender, EventArgs e)
{
}
protected void btnNext_Click1(object sender, EventArgs e)
{
int buton = Convert.ToInt32(Session["buttonIndex"]);
if (buton < 5)
{
if (RadioButtonList1.SelectedIndex + 1 == Convert.ToInt32(Session["Answer"]))
{
int marks = Convert.ToInt32(Session["Marks"]);
marks++;
Session["Marks"] = marks;
}
Session["buttonIndex"] = Convert.ToInt32(Session["buttonIndex"]) + 1;
renderQuestions(Convert.ToInt32(Session["buttonIndex"]));
if (buton == 4)
{
Server.Transfer("Results.aspx");
Session.RemoveAll();
}
}
}
}
this is my HTML
<form id="form1" runat="server">
<div>
<h3>Please choose the right answer</h3>
</div>
<table class="style1">
<tr>
<td class="style3">
<asp:Panel ID="Panel1" runat="server">
<asp:Label ID="lblQuestion" runat="server" Text=""></asp:Label>
</asp:Panel>
</td>
<td class="style4">
</td>
</tr>
<tr>
<td class="style2">
Answers:</td>
<td>
</td>
</tr>
<tr>
<td class="style2">
<asp:Panel ID="Panel2" runat="server">
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
</asp:RadioButtonList>
<asp:RadioButton ID="option1" runat="server" Checked="false" AutoPostBack="True"
GroupName="Option" oncheckedchanged="option1_CheckedChanged" />
<asp:RadioButton ID="option2" runat="server" Checked="false" AutoPostBack="True"
GroupName="Option" oncheckedchanged="option2_CheckedChanged" />
<asp:RadioButton ID="option3" runat="server" Checked="false" AutoPostBack="True"
GroupName="Option" oncheckedchanged="option3_CheckedChanged" />
<asp:RadioButton ID="option4" runat="server" Checked="false" AutoPostBack="True"
GroupName="Option" oncheckedchanged="option4_CheckedChanged" />
</asp:Panel>
</td>
<td>
</td>
</tr>
<tr>
<td class="style2">
</td>
<td>
</td>
</tr>
<tr>
<td class="style2">
<asp:Button ID="btnNext" runat="server" onclick="btnNext_Click1" Text="Next" />
</td>
<td>
</td>
</tr>
</table>
</form>
I got the result perfect and no issues yet.But i want to make sure am doing the best way and do my code meet the standards and is there any security issues.
Please some one guide me through this if u can.Thanks in advance.

How to write a function that can be available in all Razor views?

I'm trying to write a function that can bring a language resource from database in MVC 5 and Razor,
I want it to be very simple to use, for example, the following function should just get some text:
#T("ResourceType", "ResourceName")
I don't want to use #this. - just the the function name...
I saw some posts about it mentioning the line below, but still trying to understand how to do it
public abstract class WebViewPage<TModel> : System.Web.Mvc.WebViewPage<TModel>
Any help will be greatly appreciated.
Thanks in advance.
I finally found a way to do it, inspired by the NopCommerce project, see the code below.
The code can be used in any Razor (cshtml) view like this:
<h1>#T("StringNameToGet")</h1>
Also, note that pageBaseType needs to be updated with the correct new namespace,
this is the web.config in the Views folder - not the main one, should look like this:
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="MyNameSpace.Web.Extensions.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization"/>
<add namespace="System.Web.Routing" />
<add namespace="APE.Web" />
</namespaces>
</pages>
The code:
namespace MyNameSpace.Web.Extensions
{
public delegate LocalizedString Localizer(string text, params object[] args);
public abstract class WebViewPage : WebViewPage<dynamic>
{
}
/// <summary>
/// Update the pages element /views/web.config to reflect the
/// pageBaseType="MyNameSpace.Web.Extensions.WebViewPage"
/// </summary>
/// <typeparam name="TModel"></typeparam>
public abstract class WebViewPage<TModel> : System.Web.Mvc.WebViewPage<TModel>
{
private Localizer _localizer;
/// <summary>
/// Get a localized resources
/// </summary>
public Localizer T
{
get
{
if (_localizer == null)
{
//null localizer
//_localizer = (format, args) => new LocalizedString((args == null || args.Length == 0) ? format : string.Format(format, args));
//default localizer
_localizer = (format, args) =>
{
var resFormat = SampleGetResource(format);
if (string.IsNullOrEmpty(resFormat))
{
return new LocalizedString(format);
}
return
new LocalizedString((args == null || args.Length == 0)
? resFormat
: string.Format(resFormat, args));
};
}
return _localizer;
}
}
public string SampleGetResource(string resourceKey)
{
const string resourceValue = "Get resource value based on resourceKey";
return resourceValue;
}
}
public class LocalizedString : System.MarshalByRefObject, System.Web.IHtmlString
{
private readonly string _localized;
private readonly string _scope;
private readonly string _textHint;
private readonly object[] _args;
public LocalizedString(string localized)
{
_localized = localized;
}
public LocalizedString(string localized, string scope, string textHint, object[] args)
{
_localized = localized;
_scope = scope;
_textHint = textHint;
_args = args;
}
public static LocalizedString TextOrDefault(string text, LocalizedString defaultValue)
{
if (string.IsNullOrEmpty(text))
return defaultValue;
return new LocalizedString(text);
}
public string Scope
{
get { return _scope; }
}
public string TextHint
{
get { return _textHint; }
}
public object[] Args
{
get { return _args; }
}
public string Text
{
get { return _localized; }
}
public override string ToString()
{
return _localized;
}
public string ToHtmlString()
{
return _localized;
}
public override int GetHashCode()
{
var hashCode = 0;
if (_localized != null)
hashCode ^= _localized.GetHashCode();
return hashCode;
}
public override bool Equals(object obj)
{
if (obj == null || obj.GetType() != GetType())
return false;
var that = (LocalizedString)obj;
return string.Equals(_localized, that._localized);
}
}
}

ASP.NET runtime error:code blocks are not supported in this context-with ListView

i have this listView and textBox:
<table>
<tr><td>Reciver:<table><tr>
<asp:ListView ID="showRecivers" runat="server"><td><%# Eval("name")%></td> </asp:ListView>
</tr></table>
<asp:TextBox ID="reciver" runat="server" OnTextChanged="style_Recivers" AutoPostBack="true"></asp:TextBox>
</td></tr></table>
the list the listview is bound to:
public List<Reciver> recivers = new List<Reciver>();
and the function style_Recivers:
protected void style_Recivers(object sender, EventArgs e)
{
string[] separator = new string[] { "," };
string[] reciversArray = reciver.Text.ToString().Split(separator, StringSplitOptions.None);
reciversArray = reciversArray.Distinct().ToArray();
for (int i = 0; i < reciversArray.Length; i++)
{
recivers.Add(new Reciver(reciversArray[i]));
}
this.showRecivers.DataSource = recivers;
this.showRecivers.DataBind();
}
and class Reciver:
public class Reciver
{
public string name;
public Reciver(string name)
{
this.name = name;
}
public string getName()
{
return this.name;
}
public void setName(string name)
{
this.name = name;
}
}
what my idea is, that when a couple of names eneted to the textBox with a , saperator, the style_Reciver function is activated and each name is shown in the ListView right away.
but it doesnt work, it gives me the error
ASP.NET runtime error:code blocks are not supported in this context
and marks this line:
<asp:ListView ID="showRecivers" runat="server"><td><%# Eval("name")%></td> </asp:ListView>
for starter. probably more thing wont work but this is the first thing.
how can i fix it? Thanks for the help
EDIT:
it works after i added <ItemTemplate>
now it gives me a different bug:
Reciver' does not contain a property with the name 'name'
whhat is the problem now?
The List View content here should be wrapped into ItemTemplate:
<asp:ListView ID="showRecivers" runat="server">
<ItemTemplate>
<td><%# Eval("name")%></td>
</ItemTemplate>
</asp:ListView>
Update. Also there is a problem with your class declaration. Here is how it should be declared in C# conventional way:
public class Reciver
{
public string _name;
public Reciver(string name)
{
this.name = name;
}
public string name
{
get { return this._name; }
set { this._name = value; }
}
}

Unmarshalling array of complex JSON objects with MOXy JAXB 2.5.1

I'm trying to use MOXy JAXB to unmarshal some JSON/XML in an Apache CFX project. The following request gives me trouble:
{"CC.ConsumerPersistAppDataRequest" : {
"SessionId" : "42",
"AppData" : [
{"AppDatum" : {
"TimeStamp" : 1384548486,
"Value" : "Some kind of String would go here"}},
{"AppDatum" : {
"TimeStamp" : 1384548578,
"Value" : "I hope I am understanding this format correctly!"}},
{"AppDatum" : {
"TimeStamp" : 1384549696,
"Value" : "One more time for the road..."}}],
"MetaDataTags" : ["dumb", "dummy", "data"]}
}
Here, AppData is unmarshalled as a List<AppDatum>, however the list only contains the last element. Notably, the "MetaDataTags" element is correctly unmarshalled as a List<String> of size 3.
Surprisingly, the following request can be submitted with the same result, despite the fact the "AppData" should expect a List<AppDatum> (I can't help but feel this is related):
{"CC.ConsumerPersistAppDataRequest" : {
"SessionId" : "42",
"AppData" : {
"AppDatum" : {
"TimeStamp" : 1384548486,
"Value" : "Some kind of String would go here"
}
}
}}
This XML equivalent (or what I see to be the XML equivalent) is parsed as expected:
<?xml version="1.0" encoding="UTF-8"?>
<cc:ConsumerPersistAppDataRequest xmlns:cc="http://org/alg/ari/pnd/introspect/webservices/consumercomms">
<SessionId>42</SessionId>
<AppData>
<AppDatum>
<TimeStamp>1384548486</TimeStamp>
<Value>Some kind of String would go here</Value>
</AppDatum>
<AppDatum>
<TimeStamp>1384548578</TimeStamp>
<Value>I hope I am understanding this format correctly!</Value>
</AppDatum>
<AppDatum>
<TimeStamp>1384549696</TimeStamp>
<Value>One more time for the road...</Value>
</AppDatum>
</AppData>
<MetaDataTags>dumb dummy data</MetaDataTags>
</cc:ConsumerPersistAppDataRequest>
The JAXB class in question (generated by XJC, comments elided):
package org.alg.ari.pnd.introspect.webservices.consumercomms;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlList;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"sessionId",
"appData",
"metaDataTags"
})
#XmlRootElement(name = "ConsumerPersistAppDataRequest")
public class ConsumerPersistAppDataRequest {
#XmlElement(name = "SessionId", required = true)
protected String sessionId;
#XmlElement(name = "AppData", required = true)
protected ConsumerPersistAppDataRequest.AppData appData;
#XmlList
#XmlElement(name = "MetaDataTags", required = true)
protected List<String> metaDataTags;
public String getSessionId() {
return sessionId;
}
public void setSessionId(String value) {
this.sessionId = value;
}
public ConsumerPersistAppDataRequest.AppData getAppData() {
return appData;
}
public void setAppData(ConsumerPersistAppDataRequest.AppData value) {
this.appData = value;
}
public List<String> getMetaDataTags() {
if (metaDataTags == null) {
metaDataTags = new ArrayList<String>();
}
return this.metaDataTags;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"appDatum"
})
public static class AppData {
#XmlElement(name = "AppDatum", required = true)
protected List<ConsumerPersistAppDataRequest.AppData.AppDatum> appDatum;
public List<ConsumerPersistAppDataRequest.AppData.AppDatum> getAppDatum() {
if (appDatum == null) {
appDatum = new ArrayList<ConsumerPersistAppDataRequest.AppData.AppDatum>();
}
return this.appDatum;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"timeStamp",
"value"
})
public static class AppDatum {
#XmlElement(name = "TimeStamp")
protected long timeStamp;
#XmlElement(name = "Value", required = true)
protected String value;
public long getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(long value) {
this.timeStamp = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
}
and my MoxyJsonProvider bean
<bean id="moxy-json-provider"
class="org.eclipse.persistence.jaxb.rs.MOXyJsonProvider">
<property name="attributePrefix" value="#" />
<property name="formattedOutput" value="true" /> <!-- set to false for production! -->
<property name="includeRoot" value="true" />
<property name="marshalEmptyCollections" value="false" />
<property name="valueWrapper" value="$" />
<property name="namespacePrefixMapper" ref="json-ns-mapper" />
</bean>
Any idea what could be causing this issue? Is this a bug in the 2.5.1 Release of MOXy? Or is there a "switch" somewhere that I need to set?
Based on your mapping, the folloiwng would be the expected JSON document:
{
"CC.ConsumerPersistAppDataRequest" : {
"SessionId" : "42",
"AppData" : {
"AppDatum" : [ {
"TimeStamp" : 1384548486,
"Value" : "Some kind of String would go here"
}, {
"TimeStamp" : 1384548578,
"Value" : "I hope I am understanding this format correctly!"
}, {
"TimeStamp" : 1384549696,
"Value" : "One more time for the road..."
} ]
},
"MetaDataTags" : "dumb dummy data"
}
}
The following is the standalone example I wrote based on yours to read in the XML and output the corresponding JSON:
import java.io.File;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.MarshallerProperties;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(ConsumerPersistAppDataRequest.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum20056524/input.xml");
ConsumerPersistAppDataRequest result = (ConsumerPersistAppDataRequest) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
marshaller.setProperty(MarshallerProperties.JSON_ATTRIBUTE_PREFIX, "#");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
marshaller.setProperty(MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, false);
marshaller.setProperty(MarshallerProperties.JSON_VALUE_WRAPPER, "$");
Map<String, String> jsonNsMapper = new HashMap<String, String>(1);
jsonNsMapper.put("http://org/alg/ari/pnd/introspect/webservices/consumercomms", "CC");
marshaller.setProperty(MarshallerProperties.NAMESPACE_PREFIX_MAPPER, jsonNsMapper);
marshaller.marshal(result, System.out);
}
}

Tapestry: How to write HTML from java page

I need to write HTML from my .java page. Here is what I have tried
This is my tml code fragment
${testFunction()}
This is my java code fragment
public String testFunction()
{
return "<input type='checkbox' name='leaf' id='leaf' value='leaf'/>"
}
The result I want is a checkbox. What I get is a string "input type='checkbox' name='leaf' id='leaf' value='leaf'".
Any help would be appreciated Thanks.
If you want to render string as html you need to use MarkupWriter#writeRaw() method:
void beginRender(MarkupWriter writer) {
writer.writeRaw("<input type='checkbox' name='leaf' id='leaf' value='leaf'/>");
}
Or you can use OutputRaw component:
<t:outputraw value="testFunction()"/>
Or you can use Renderable to write markup:
#Property(write = false)
private final Renderable checkbox = new Renderable() {
public void render(MarkupWriter writer) {
writer.element("input",
"type", "checkbox",
"id", "leaf",
"name", "leaf",
"value", "leaf");
writer.end();
// if you need checked attribute
// writer.getElement().attribute("checked", "checked");
}
};
And on template:
<t:delegate to="checkbox"/>