RazorScript Count Not Working - razor

I am using DNN and have (with the help of a co-worker) created a script to print out items from the Form and List module, but need to limit the output to three. However, the script returns nothing. Can anyone point to me where I may have gone wrong?
http://jsfiddle.net/VsF6c/
#using System.Data;
#using DotNetNuke.Entities.Modules;
#using DotNetNuke.Entities.Portals;
#using DotNetNuke.Modules.UserDefinedTable;
#using DotNetNuke.Entities.Users;
#{
var mc = new ModuleController();
var tc = new DotNetNuke.Entities.Tabs.TabController();
int portalId = PortalController.GetCurrentPortalSettings().PortalId;
var flModule = mc.GetModuleByDefinition(portalId, "Form and List");
int moduleId = -1;
int tabId = -1;
var tab = tc.GetTabByName("News", portalId);
if (tab != null) {
tabId = tab.TabID;
}
if (flModule != null) {
moduleId = 968;
}
var ds = (new UserDefinedTableController(moduleId, tabId, new UserInfo())).GetDataSet(true);
}
<ul>
#for (int i = 0; i < 3; i++)
{
DataRow row = ds.Tables["Data"].Rows[i];
<li>
<a href='/news##row["UserDefinedRowId"]' title='#row["Title"]'>#row["Title"]</a>
</li>
}
</ul>

Related

How to generate Checkboxlist dynamically using ASP.NET Literal

I'm trying to generate checkboxlist dynamically using this code:
string IDToEdit = Request.QueryString["id"].ToString();
List<DAL.EF.Dental_Price_Lists> lstOfCategDental = BAL.Helpers.Prices.GetDentalCategories();
string HTMLTag = "";
string HTMLTag2 = "";
int count = 1;
foreach (var x in lstOfCategDental)
{
HTMLTag += string.Format("<a href='#tab{0}'>{1}</a>", count, x.Category);
List<DAL.EF.Dental_Price_Lists> priceList = BAL.Helpers.Prices.GetDentalPrices(x.Category);
HTMLTag2 += string.Format("<div id='tab{0}' class='tab'>", count);
HTMLTag2 += string.Format(" <asp:CheckBoxList ID='chkListDental{0}' runat='server'>", count);
foreach (var price in priceList)
{
HTMLTag2 += string.Format(" <asp:ListItem Value='{0}' price='{1}' Text='{2}'></asp:ListItem>", price.ID.ToString(), price.Price.ToString(), price.Type);
}
HTMLTag2 += " </asp:CheckBoxList>";
HTMLTag2 += " </div>";
count++;
}
ltrCategories.Text = HTMLTag;
ltrChkListDental.Text = HTMLTag2;
}
but it didn't work correctly "explained in the below image", i think thats because the ASP.NET tag instead of the HTML tag but i'm not sure of that ... so, can you help me solve this issue?
As you see in the following image the asp.net tags didn't converted to html tags?
http://i.stack.imgur.com/ufSq3.png
You can not do it. But you can instantiate a new control and then append it the the page controls property:
foreach (var x in lstOfCategDental) {
List<DAL.EF.Dental_Price_Lists> priceList = BAL.Helpers.Prices.GetDentalPrices(x.Category);
var checkboxList = new CheckBoxList();
checkboxList.ID = string.Format("chkListDental{0}", count);
foreach (var price in priceList) {
var listItem = new ListItem(price.Type);
listItem.Value = price.ID.ToString();
checkboxList.Attributes.Add("price", price.Price.ToString());
checkboxList.Items.Add(listItem);
}
count++;
Page.Controls.Add(checkboxList);
}
or use the RenderControl method of the control for each of the controls, but it is not recommended.
StringBuilder sb = new StringBuilder();
StringWriter stWriter = new StringWriter(sb);
HtmlTextWriter htmlWriter = new HtmlTextWriter(stWriter);
ControlToRender.RenderControl(htmlWriter);
.
.
.
foreach (var x in lstOfCategDental) {
List<DAL.EF.Dental_Price_Lists> priceList = BAL.Helpers.Prices.GetDentalPrices(x.Category);
var checkboxList = new CheckBoxList();
checkboxList.ID = string.Format("chkListDental{0}", count);
foreach (var price in priceList) {
var listItem = new ListItem(price.Type);
listItem.Value = price.ID.ToString();
checkboxList.Attributes.Add("price", price.Price.ToString());
checkboxList.Items.Add(listItem);
}
count++;
checkboxList.RenderControl(htmlWriter);
}
ltrChkListDental.Text = sb.ToString();
I solved it by creating the div dynamically too then add the checkboxlist to that div.
string IDToEdit = Request.QueryString["id"].ToString();
List<DAL.EF.Dental_Price_Lists> lstOfCategDental = BAL.Helpers.Prices.GetDentalCategories();
string HTMLTag = "";
int count = 1;
foreach (var x in lstOfCategDental)
{
var checkboxList = new CheckBoxList();
List<DAL.EF.Dental_Price_Lists> priceList = BAL.Helpers.Prices.GetDentalPrices(x.Category);
HTMLTag += string.Format("<a href='#tab{0}'>{1}</a>", count, x.Category);
checkboxList.ID = string.Format("chkListDental{0}", count);
HtmlGenericControl divControl = new HtmlGenericControl("div");
// Set the properties of the new HtmlGenericControl control.
divControl.ID = "tab" + count;
divControl.Attributes.Add("class", "tab");
// Add the new HtmlGenericControl to the Controls collection of the
// PlaceHolder control.
divPlaceHolder.Controls.Add(divControl);
foreach (var price in priceList)
{
var listItem = new ListItem(price.Type);
listItem.Value = price.ID.ToString();
checkboxList.Attributes.Add("price", price.Price.ToString());
checkboxList.Items.Add(listItem);
}
count++;
divControl.Controls.Add(checkboxList);
}
ltrCategories.Text = HTMLTag;

max lengt or else dots - How or what should i write?

I want the script to show max 26 letters and if there is more I want it to make (...) <-- so that you can se there is more letters in the link.
First I put a bit of a script I have for another site containing a variable to do that, however it doesn't work in RSS:
{
temp.Add(titel);
count++;
string titel_kort = titel;
if (titel.Length > 26)
{
titel_kort = titel.Substring(0, 26) + "...";
}
}
And this is the script I want to integrate to:
#using System.Xml.XPath;
#using System.Xml;
#{
try
{
XmlTextReader udBrudRSS = new XmlTextReader("http://tidende.dk/rss.aspx");
XmlDocument doc = new XmlDocument();
doc.Load(udBrudRSS);
XmlNodeList rssItems = doc.SelectNodes("//item");
var count = 0;
foreach (XmlNode node in rssItems )
{
count++;
if (count > 3) { break; }
<div class="nyhedlink">- #node["title"].InnerText</div>
}
}
catch {}
}
You could something like this :
using (var webclient = new WebClient())
{
var data = webclient.DownloadData("http://tidende.dk/rss.aspx");
var oReader = new XmlTextReader(new MemoryStream(data));
var xml = XDocument.Load(oReader);
var values = xml.XPathSelectElements("//item").Take(3).Select(p => new
{
Link = p.XPathSelectElement("//link").Value,
Title = (p.XPathSelectElement("./title").Value.Length > 26) ?
p.XPathSelectElement("./title").Value.Substring(0, 26).Trim() + "..." :
p.XPathSelectElement("./title").Value.Trim()
});
foreach (var item in values)
{
<div class="nyhedlink">- #item.Title</div>
}
}
Sometimes is better use WebClient to make the petition instead of XmlTextReader see this question for a good explanation.

how to insert record to multiple tables with multiple file with linq2sql

I have web application in asp.net 3.5. I just want to add record to 3 tables and one table contains multiple file details that I associated with table primary key value.
For more info I include this code:
protected void submit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
int user_id = 0;
var query = from u in db.Users
where u.Username == (String)Session["Username"]
select new
{
Id = u.Id
};
foreach (var item in query)
{
if (item != null)
{
user_id = int.Parse(item.Id.ToString());
break;
}
}
Post myPost = new Post();
myPost.Title = txt_ComName.Text.Trim();
myPost.Category_id = int.Parse(DDL_Categorynames.SelectedItem
.Value.ToString());
myPost.Description = txt_ComName1.Text.Trim();
myPost.User_id = user_id;
myPost.ToUser_id = user_id;
if(file_upload.HasFile)
{
myPost.IsFileAttached = true;
}
else
{
myPost.IsFileAttached = false;
}
db.Posts.InsertOnSubmit(myPost);
db.SubmitChanges();
int newId = myPost.Id;
Flag myFlag = new Flag();
myFlag.IsRead = false;
myFlag.IsImportant = false;
myFlag.IsRemoved = false;
myFlag.User_id = user_id;
myFlag.Post_History_id = newId;
db.Flags.InsertOnSubmit(myFlag);
db.SubmitChanges();
File myFile = new File();
HttpFileCollection fileCollection = Request.Files;
for (int i = 0; i < fileCollection.Count; i++)
{
HttpPostedFile uploadfile = fileCollection[i];
string fileName = Path.GetFileName(uploadfile.FileName);
string fileType = System.IO.Path.GetExtension(fileName)
.ToString().ToLower();
myFile.Post_History_id = newId;
myFile.File_name = fileName;
myFile.File_ext = fileType;
myFile.File_Size = uploadfile.ContentLength.ToString();
if (uploadfile.ContentLength > 0)
{
uploadfile.SaveAs(Server.MapPath("~/PostFiles/")
+ fileName);
db.Files.InsertOnSubmit(myFile);
db.SubmitChanges();
}
}
Panel_AddNew.Visible = false;
Panel_ViewPostList.Visible = true;
this.FillGrid();
}
}
}
However, with this scenario first file that was selected that was inserted and after that second file iterated then error occurred like:
Cannot add an entity that already exists.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Cannot add an entity that already exists.
Source Error:
Line 248: {
Line 249: uploadfile.SaveAs(Server.MapPath("~/PostFiles/") + FileName);
Line 250: db.Files.InsertOnSubmit(myFile);
Line 251: db.SubmitChanges();
Line 252: }
Source File: f:\EasyWeb\EndUser\Post_History.aspx.cs Line: 250
please help me...
Create a new File in each iteration of the foreach loop:
for (int i = 0; i < fileCollection.Count; i++)
{
File myFile = new File();
HttpPostedFile uploadfile = fileCollection[i];
...

How to know if a NodeFactory node is published

#inherits Umbraco.Web.Mvc.UmbracoTemplatePage
#using umbraco.NodeFactory;
#using umbraco.MacroEngines;
<ul class="rslides">
#{
var rootNode = Model.Content.AncestorOrSelf(1);
var items = (rootNode.HasValue("featuredSlides")) ? (Umbraco.Core.Dynamics.DynamicXml)rootNode.GetPropertyValue("featuredSlides") : null;
}
#if (items != null)
{
foreach(var item in items)
{
int id = Convert.ToInt32(#item.InnerText);
Node node = new Node(id);
var mediaItem = Umbraco.TypedMedia(node.GetProperty("picture").ToString());
int mediaHeight = Convert.ToInt16(#mediaItem.GetPropertyValue("umbracoHeight"));
int maxHeight = 700;
int height = (mediaHeight > maxHeight) ? maxHeight : mediaHeight;
var url = #node.Url;
<li><img src="/imagegen.ashx?image=#mediaItem.GetPropertyValue("umbracoFile")&width=640"></li>
}
}
</ul>
I would like to know what is the published status of #node.
I'm working with umbraco 6.1.6
I already tried something like var p = #node.GetProperty("published") (publishedCount, publishedStatus ...) but nothing worked.
Any idea?
Thanks.
(Dynamic)Node gives access to (only) published content from the XML cache. Node has properties CreateDate and UpdateDate.

How to add required attendees in appoitment in microsoft crm

I added a new contact in microsoft dynamics 4.0 from C#. How to required attendees from code? I created a contact like this. now how to add this contact as required attendees for selected appointment ?
CRM.CrmService service = GetService();
var contactResult = new contact
{
emailaddress1 = userContact.Email
};
var requestContact = new RetrieveDuplicatesRequest
{
BusinessEntity = contactResult
,
MatchingEntityName = EntityName.contact.ToString()
,
PagingInfo = new PagingInfo
{
PageNumber = 1,
Count = 1
}
};
bool blnEmailExists = false;
try
{
var response = (RetrieveDuplicatesResponse)
service.Execute(requestContact);
foreach (contact contactItem in response.DuplicateCollection.BusinessEntities)
{
blnEmailExists = true;
contactResult.contactid = new Key();
contactResult.contactid.Value = new Guid(contactItem.contactid.Value.ToString());
contactResult.firstname = userContact.FirstName;
contactResult.lastname = userContact.LastName;
contactResult.fullname = userContact.FullName;
contactResult.mobilephone = userContact.PhoneNumber;
contactResult.description = userContact.Description;
service.Update(contactResult);
}
if (!blnEmailExists)
{
contactResult.firstname = userContact.FirstName;
contactResult.lastname = userContact.LastName;
contactResult.fullname = userContact.FullName;
contactResult.mobilephone = userContact.PhoneNumber;
contactResult.description = userContact.Description;
Guid contactId = service.Create(contactResult);
if (!string.IsNullOrEmpty(userContact.Notes))
AppendToNotesSection(userContact.Notes, contactId, service);
}
}
catch (System.Web.Services.Protocols.SoapException ex)
{
throw new Exception(ex.Message);
}
Thanks
Through activityParty it can be updated, atlast i found it and fixed.
CRM.CrmService service = GetService();
appointment appointment = (appointment)service.Retrieve(EntityName.appointment.ToString(), activityid, new AllColumns());
if(appointment == null)
{
throw new ArgumentNullException("Invalid Appointment");
}
contact contact = RegisterContact(userContact, service);
activityparty[] activityParty = new activityparty[appointment.requiredattendees.Length + 1];
activityParty[0] = new activityparty();
activityParty[0].partyid = new Lookup();
activityParty[0].partyid.Value = contact.contactid.Value;
activityParty[0].partyid.type = "contact";
Int16 index = 1;
foreach (var item in appointment.requiredattendees)
{
//for avoiding duplicates
if (item.partyid.Value != contact.contactid.Value)
{
activityParty[index] = new activityparty();
activityParty[index].partyid = item.partyid;
activityParty[index].partyid.Value = item.partyid.Value;
activityParty[index].partyid.type = item.partyid.type;
index++;
}
}
appointment.requiredattendees = activityParty;
try
{
service.Update(appointment);
}
catch (System.Web.Services.Protocols.SoapException ex)
{
Console.WriteLine(ex.Message + ". " + ex.Detail.InnerText);
}