Posts

Showing posts with the label ASP .Net

The <link> saga on ASP .Net

Image
Indeed, there is a saga. Since from the very beginning of my ASP .Net experiences I had to deal with the "CSS problem". This problem occurs when the referenced CSS is not loaded, because the relative path is not given right. We place in the Master Page all the common html used in the website, including the links to the CSS files. Pages might be placed in different nested folders and because of this, the link to the CSS file needs to be adjusted with the relative prefixes. Since the link is placed in the Master Page and it is not known in advantage the website structure, the solution should solve the problem of how is the right prefix added to the CSS link. HTML introduced Relative Uniform Resource Locators ( see [Page 11]) which actually solves this problem. Instead of writing the absolute paths (ie. http://www.mysite.com/public/main.css ), it suffices to use the relative paths, like public/main.css. That RFC explains the algorithm of how the prefixes ( /, ./, ../, ../../ so...

Working with TIME type in SQL and ASP .Net

Scenario: a teacher schedules his courses on a random different dates in the near future, but he always know the start time. For sample in the current week he can schedule a course for Tuesday and Friday, at 08:00 AM. In a database there would be the following tables: 1. course (title, summary, ..) 2. c ourse_schedule(course_id, location, start_time) where data about that schedule is preserved( ie. location) 3. course_schedule_span(schedule_id, course_date) for storing the dates when the schedule spans The dates have always the same start time, I knew this before designing the database, so in the first time I let the time in the course_schedule_span table, in course_date column (ie. 31/12/2011 16:00). Later the teacher wanted to set and the end time so I decided to move the start time into course_schedule table and this new end time field to add it there also. The first attempt was to store the time in a varchar(5) column, this would suffice for storing like hh:mm values. Later I ch...

About the "The Controls collection cannot be modified because the control contains code blocks" symptom

As the error message says, if a control contains code blocks (but not databinding expressions, ie <%# ..), its Controls collection can't be altered, by adding another control at runtime using Controls.Add. However, this rule doesn't apply for child controls, for example if a control uses other control with code blocks, then the first control's Controls collection (the parent's one) has no limitations. Usually this error is encountered mostly when working with the <head runat="server". Suppose there is a code block which uses some code to decide which protocol to use to download some external scripts, depending on the connection used by the client. <head runat="server"> <% if (!HttpContext.Current.Request.IsSecureConnection) { %> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script> <% } else {%> <script src="https://ajax.goo...

ListView Alternating Group Template

The ListView have no such thing as alternating the group templates and still is so much needed. public class aiListView : ListView { int groupDisplayIndex = 1; /*update on June 16, 2010*/ private ITemplate _alternatingGroupTemplate; public virtual ITemplate AlternatingGroupTemplate { get { return _alternatingGroupTemplate; } set { _alternatingGroupTemplate = value; } } protected override void InstantiateGroupTemplate(System.Web.UI.Control container) { ITemplate template = this._alternatingGroupTemplate; if (_alternatingGroupTemplate != null && GroupItemCount > 0 && groupDisplayIndex % 2 == 0 /*update on June 16, 2010*/) { template = this._alternatingGroupTemplate; } else { template = this.GroupTemplate; } template.I...

ASP .Net server control for youtube embeded videos

Here is ASP .Net server control for youtube embeded videos. The param definitions can be found here Only Src param is required, other parameters are generated only if have another value than the default one. Usage <cc1:YouTubeEmbed ID="YouTubeEmbed1" runat="server" Src="http://www.youtube.com/v/P38oxTrWYp0&f=videos&c=ytapi-AdrianIftode-youtubelyricsmas-ia9d2g0e-0" AutoPlay="false" AllowFullScreen="false" Border="true" PrimaryBorderColor="0x6b8ab6" SecondayBorderColor="0x2b405b" GenieMenu="true" HighDefinitionPlayback="false" LoadRelatedVideos="false" Loop="false" ShowAnnotations="true" ShowClosedAnnotations="true" ShowInfo="false" ...

Tracking codes in DEBUG-RELEASE mode

While you work on a website which includes some JavaScript for counters and statistics is better not to allow or to "hide" them during the development time. One solution is to comment the source code and every time before the page is published, to uncomment the relevant lines. This leads to errors sooner or later, we use to forget things (uncomment things). A better option is to use preprocessor directives #if, #endif with the DEBUG compile option. A protected(at least) boolean field must be added in the code behind. public partial class home : System.Web.UI.Page { #if (DEBUG) protected static readonly bool Debug = true; #else protected static readonly bool Debug = false; #endif } Now the field Debug can be used in the web form. The following google analytics code will exist only when the source code is compiled in Release mode. <%if (!Debug) { %> <script type="text/javascript"> var gaJsHost = (("https:" ...

Eval: Sometimes I like spagheti code

I just discovered some interesting features of the construct . Eval function uses reflection to evaluate a property of a bound object. I have two classes Product and Category and I want to display the available products in a page, by using a data bound control. public class Product { public int ID; public string Name; public int Stock; public DateTime Date; public Category Category; } public class Category { public string Name; public DateTime Date; } In a data template ( ItemTemplate for sample ) I can use the Eval function like: 1. very simple evaluation without using formats - will output the name - will output the stock ( ..and so on ) 2. using a format - for sample: 2009 Apr 06 - will output "10 items" if the stock is 10 3. Combining two or more properties: notice that the operators "+" are in the construction and the expression is not a concatenation between different constructs 4. Can use more dots! 5. Can use casting 6. What...

Un required validator pentru DropDownList cu RangeValidator

Validatorul RangeValidator va aparea in UI ca un RequiredValidator. Utilizatorul nu va putea trece mai departe daca nu alege o optiune de la 1 la 5. :) <asp:DropDownList ID="ddlTitle" runat="server"> <asp:ListItem Value="0">Select Title</asp:ListItem> <asp:ListItem Value="1">Mr</asp:ListItem> <asp:ListItem Value="2">Mrs</asp:ListItem> <asp:ListItem Value="3">Miss</asp:ListItem> <asp:ListItem Value="4">Ms</asp:ListItem> <asp:ListItem Value="5">Dr</asp:ListItem> </asp:DropDownList> <asp:RangeValidator ID="rangeValidator" Text="*" ErrorMessage="The title is required." ControlToValidate="ddlTitle" Type="Integer" MinimumValue="1" MaximumValue="5" runat="server...

JQuery si WebMethod

Prin noiembrie 2006 descoperisem la HALO interactive posibilitatea de a apela dintr-o pagina HTML o metoda dintr-o pagina aspx folosind un ScriptManager. Trebuia sa fac o autentificare in doi pasi. ScriptManger-ul genereaza ceva JavaScript folosit pentru a construi apelul AJAX, dar si pentru a folosi o sintaxa de genul PageMethods.MethodName, valabila atata timp cat e setata true optiunea EnablePageMethods. Mult mai usor de scris e insa atunci cand se foloseste JQuery. O dezbatere am gasit aici . Vreau doar sa dau un exemplu intersant de folosit intr-un shopping cart. Intr-un astfel de site exista cred mai multe pagini statice, decat dinamice. Adica fizic mai multe html-uri decat aspx-uri. Acum pe fiecare pagina html sau aspx apare undeva in pagina numarul de produse puse in cos. Daca ar fi sa se aleaga Master Pages pentru a-l afisa, odata ce se adauga o pagina noua in site trebuie recompilat tot situl. Solutia cea mai buna e sa se foloseasca AJAX. Partea frumoasa e ca poti face cumpar...

Despre CompositeDataBoundControl

CompositeDataBoundControl este clasa de baza pentru DetailsView, FormView si GridView si are o metoda abstracta ce trebuie implementata de orice clasa mostenitoare. protected abstract int CreateChildControls(IEnumerable dataSource, bool dataBinding); dataBinding reprezinta: -true: controlul va fi construit pe baza unui dataSource -false: controlul se va reconstrui din ViewState DetailsView, FormView sau GridView ofera diverse templaturi: de edit, de view sau atunci cand nu exista date in dataSource poti sa arati un anumit mesaj ce prezinta aceasta stare. Ca idee un template face legatura intre date si HTMLul scris de developer la design time, adica separa prezentarea de implementare. Din urmatorul Xml, care reprezinta organizarea unei anumite firme, as vrea sa obtin un control care sa arate ierarhia din acea firma, adica un fel de tree. Xmlul are 3 niveluri: Managers urmat de Sales, Development si Administrative, fiecare la randul lui avand alte diverse categorii de angajati. Fiecare ...

IsPostBack

MSDN spune ca proprietatea IsPostBack e o valoare care indica daca pagina este creata pentru a fi raspunsul postbackului unui client sau pagina este creata si accesata pentru prima data. Cuvantul cheie e postback, de fapt ce inseamna acest postback. Perceptia generala e ca IsPostBack e true atunci cand utilizatorul da click pe un buton sau pe un control dintr-o anumita pagina, care are setata proprietatea AutoPostBack = true (dropdown de exemplu).. sau hai sa zicem pe orice control cu evenimente care se instantiaza pe server in urma unei actiuni a utilizatorului in fereastra browserului. Mai altfel zis, Popescu, avid de monden, deschide browseru, scrie http://www.web.com/Clasamente.aspx, ii apare pagina frumoasa, care il invita sa dea click pentru a vedea clasamentul celor mai naspa vedete din Romania. Developerul presupune la PageLoad ca Page.IsPostBack e true, adica Popescu sigur avea deja pagina incarcata in browser, inainte de a accesa clasamentul celor mai naspa vedete din Romani...

LINQ to XML in ASP .Net

Image
Un alt mod de a stoca si manipula date este familia XML. Datele din fisiere sunt constranse sa respecte un anumit model, prin schemele XSD. Cu XPath se colecteaza date, iar cu XSLT fisierul sau setul de noduri se "converteste" in alt model de reprezentare (HTML, XML,..). Am imprumutat o parte din baza de date Northwind din SQL si am construit un fisier XML care contine un model relational. Astfel exista o lista de noduri de tip "produs" (tabela Products),o lista de tip "categorie" (tabela Categories) si o lista de noduri de tip "furnizor" (tabela Suppliers). Fiecare lista contine cate o cheie primara (xs:key). Pentru lista "Products" sunt definite chei straine care referentiaza la elemente din listele "Categories" sau "Suppliers" (xs:keyref). Cu xs:unique s-a constrans ca numele categoriilor/furnizorilor sa fie unic (Unique Constraint in SQL). Fisier xml: lista de produse, categorii si furnizori. <?xm...