Thursday, June 7, 2012

Expression Blend 4 does not open design mode for Silverlight Navigation Application.

When you are trying to open a .xaml file in expression blend from visual stodio, whether the design view will be loaded or not, will depend on the type of the project. In same cases, you need to edit the .csproj file by adding this code in the first line of the property group:

<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}</ProjectTypeGuids>

However, that did not solve the problem in my case. I was using silverlight 5, and expression blend 4. From visual studio 2010, I need to change the "Target Silver Light version" to silverlight 4 from the properties of the project, only then I could open .xaml pages in expression blend with design view.

Thursday, July 15, 2010

UltraWebGrid Get the current Filter Item from javascript

I had a problem where I needed to find which filter item I have chosen from the filter drop down. It's easy to get this from server side:

((Infragistics.WebUI.UltraWebGrid.FilterCondition)(e.ActiveColumnFilter.FilterConditions.GetItem(0))).CompareValue

But it seemed pretty difficult to find it from cilent side. In the end, I managed to find it. I used the "BeforeRowFilterApplied" client side event :

function UltraWebGrid1_BeforeRowFilterApplied(gridName, oColumn)
{ $get("<%=tbFilterOperand.ClientID%>").value=oColumn.Band.Grid._currentFilterDropped._evaluationValue;
}

It returned the filter item item (operand) that has been selected. I stored it inside the text field "tbFilterOperand" for later use.

Wednesday, June 23, 2010

Validation expression to check Minimum length of 5 with trimming both ends

After spending some time I've been able to derive this expression:

ValidationExpression="^[\s]*[\x21-\x7E][\x20-\x7E]{3,}[\x21-\x7E][\s]*$"

It ignores if there is space/ tab at the beginning or at the end of the string. But it adds spaces in account if they come in between the beginning and ending charaters.

Thursday, February 18, 2010

Check Page.IsPostBack from Javascript

This cannot be done alone from Javascript. We need to use some help from the server file as well.

1. Add Postback check in the server file:

In the page_load of server file, Add this code:

if (!Page.IsPostBack)
{
string Script = "var ranOnce = false;";
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "InitVariable", Script, true);
}

As we know !Page.IsPostBack check restricts execution to enter into the "if" block more than once after page has been loaded. We are declaring a javascript variable "ranOnce" from this block. RegisterClientScriptBlock adds the javascript code add the begining of page script, thats why we are using it because variables should be declared before the javascript function is declared.

2. Write the rest of the code in javascript:

function Prepare() {
if(!ranOnce){
// your code here
ranOnce=true;
}
}

window.onload = Prepare;

Because the function is attached to window.onload, it will run every time, but as we set "ranOnce" to false when the execution entered for the first time it will not execute again.

Now, if page refreshes (not postback), or user navigates back from other page, then from the server side, the "ranOnce" variable will be set to false again, and the function "Prepare" will execute once again.

Thursday, January 21, 2010

Read and Write logs in XML file

If you dont want to use a DB, but still want to store, read data in a structured way, then xml is the best option. Its also used to send data over the internet.

Lets take a look at how we can create, format, read, and write data into xml file. You need to add using System.xml class with your file

1. Create an xml file:

XmlTextWriter xmltr = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
xmltr.Flush();
xmltr.Formatting = Formatting.Indented;
xmltr.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
xmltr.WriteStartElement("ComponentLog");
xmltr.Close();

We are using XmlTextWriter class to create the file. ComponentLog is the parent node in the xml file. An xml file can contain only 1 parent node.

2. Set format of the xml file:

XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNode node = doc.GetElementsByTagName("*")[0];

XmlAttribute xmlatr = doc.CreateAttribute("xmlns", "xsi", "http://www.w3.org/2000/xmlns/");
xmlatr.InnerText = "http://www.w3.org/2001/XMLSchema-instance";
XmlAttribute xmlatr2 = doc.CreateAttribute("xmlns", "xsd", "http://www.w3.org/2000/xmlns/");
xmlatr2.InnerText = "http://www.w3.org/2001/XMLSchema";

node.Attributes.Append(xmlatr);
node.Attributes.Append(xmlatr2);

XmlNode SQLnode = doc.CreateElement(ComponentType.SQLServer.ToString(), null);
XmlNode IndesignNode = doc.CreateElement(ComponentType.IndesignServer.ToString(), null);
XmlNode FSNode = doc.CreateElement(ComponentType.FS.ToString(), null);
node.AppendChild(SQLnode);
node.AppendChild(IndesignNode);
node.AppendChild(FSNode);
doc.AppendChild(node);
doc.Save(filePath);

filepath is a string contains the full path of the xml file including filename and extension. We use XmlDocument to read the file first, then format it. It would obviously get only 1 node which we created earlier named "ComponentLog". Then we have added 2 attributes with this parent node. Next with this parent ode "ComponentLog" we have added 3 child nodes. We are storing 3 types of log information in the xml file. They are: SQL, Indesign, and FileSystem. That completed our formatting with the xml file.

3. Write log data into xml file:

public static void WriteXmlLog(ComponentType CType, int CStatus, string userId, string userName, string email, DateTime lastMailSent,string culturecode)
{
try
{
if (!File.Exists(filePath))
{
CreateXmlFile();
}

XmlDocument doc = new XmlDocument();

doc.Load(filePath);
XmlNodeList baseNodes = doc.GetElementsByTagName(CType.ToString());

XmlNode node = doc.CreateNode(XmlNodeType.Element, CType.ToString() + "Log", null);

XmlNode UserId = doc.CreateElement("UserId");
UserId.InnerText = userId;

XmlNode UserName = doc.CreateElement("UserName");
UserName.InnerText = userName;

XmlNode Email = doc.CreateElement("Email");
Email.InnerText = email;

XmlNode LastMailSent = doc.CreateElement("LastMailSent");
LastMailSent.InnerText = lastMailSent.ToString();

XmlNode ComponentStatus = doc.CreateElement("ComponentStatus");
ComponentStatus.InnerText = CStatus.ToString();

XmlNode Culturecode = doc.CreateElement("culturecode");
Culturecode.InnerText = culturecode;

// add children to father
node.AppendChild(UserId);
node.AppendChild(UserName);
node.AppendChild(Email);
node.AppendChild(LastMailSent);
node.AppendChild(ComponentStatus);
node.AppendChild(Culturecode);

// append the new node
baseNodes[0].AppendChild(node);

// save the file
doc.Save(filePath);
}
catch (Exception ex)
{

}
}

First, we check whether a file already exists in that path or not. If not, then we create a new one. Then, we get the node that defines type of our log. CType is the enum that defines the type of log data we will write (FS, Indesign, or SQL).
XmlNodeList baseNodes = doc.GetElementsByTagName(CType.ToString()); returns nodes that have same tagname. baseNodes[0] (Lets call this as the "typeRoot" node) will return the topmost node of that type, which is added with the parent node "ComponentLog". with the typeRoot node, we want to add log data. So basically, we have created a node named "node", created respective nodes to store info such as userId, userName, email, lastMailSent, culturecode. Then we have added this info nodes under the newly created node "node", then added "node" under the "typeRoot" node. Under the 'typeRoot" node there will be multiple entries of "node". Their tag name is same to their "typeRoot" node, just the extra "log" string is added to the end of their name. Then we save (overwrite) the existing doc file. The xml file looks like this (using IE):


4. Read from xml file:

public static DataTable ReadXML(ComponentType ctype)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
try
{
ds.ReadXml(filePath);
if (ds != null)
{
if (ctype.ToString() == ComponentType.SQLServer.ToString())
{
dt = ds.Tables[ComponentType.SQLServer.ToString() + "Log"];
}
else if (ctype.ToString() == ComponentType.IndesignServer.ToString())
{
dt = ds.Tables[ComponentType.IndesignServer.ToString() + "Log"];
}
else if (ctype.ToString() == ComponentType.FS.ToString())
{
dt = ds.Tables[ComponentType.FS.ToString() + "Log"];
}
}
}
catch
{
dt = null;
}
return dt;
}

DataSet.ReadXml("FilePath") directly reads the whole xml file in form of a dataset. Then, from the dataset we get our desired type of node collection if form of table. All the info node automatically created a column and their values created rows of the table. Thats how we read info from xml file.

Thursday, November 26, 2009

Read Page.IsValid from javascript (alternate way)

This was my scenario:
In a form there are few fields and 2 buttons :"Save" and "Cancel"
If user presses save button, and if the form validation is true, then immediately disable the "Cancel" button, so that the user cannot press the "Cancel" button. Here is the form:















"Name" field is a required field. So there is a "RequiredFieldValidator" attached with it. I have to disable the cancel button from javascript if:
1. User presses "Save" button.
2. Name field has some value (page validation passed).

To do this, I had to add a customvalidator with the name field, and do the javascript coding inside its client side function. Here is the code for the field and the validators:

<td>
<asp:TextBox ID="uxName" runat="server" MaxLength="50" width="180px"></asp:TextBox>

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="uxName" SetFocusOnError="true"
ErrorMessage="Department name cannot be empty" ValidationGroup="DepartmentEditValidation">*</asp:RequiredFieldValidator>

<asp:CustomValidator runat="server" ID="uxCustomValidator" ClientValidationFunction="checkNames" ControlToValidate="uxName" ValidationGroup="DepartmentEditValidation" ErrorMessage="" SetFocusOnError="True" Display="Dynamic">
</asp:CustomValidator>

</td>

Here is the code for Save, and Cancel button. Validation Group has to be same for the Save button.

<div class="editPanelButton">
<asp:Button ID="uxSave" runat="server" Text="<%$Resources:Texts,Save %>" ValidationGroup="DepartmentEditValidation"
OnClick="uxSave_Click" />
<asp:Button ID="uxCancel" runat="server" Text="<%$Resources:Texts,Cancel %>" OnClick="uxCancel_Click" />
<</div>

Now we need to do the javascript checking inside the clientside function of the customfield validator. We declared: ClientValidationFunction="checkNames", so here is the function:

<script type="text/javascript" >
function checkNames(source, args){

if(args.IsValid){

if(event.srcElement.id==uxSaveButtonClientId){
document.getElementById(uxCancelButtonClientId).disabled=true;
}
args.isValid=true;
}
}

</script>

args.IsValid is the alternate way of checking whether the page validation is true or not. Then I checked the validation was fired by pressing the "save" button. validation also fires when focus goes out from the "uxname" text field. So, I needed to be specific. If the conditions pass the I disabled the cancel button. This solved my problem.

Tuesday, August 25, 2009

Disable asynchronous postbacks while one asynchronous postback is active.

Asynchronous postbacks are partial postbacks occured by Ajax (or any other 3rd party) update panels. Ajax has 5 stages to handle the life cycle of an asynchronous postback. They are:

1. initializeRequest
2. beginRequest
3. pageLoading
4. pageLoaded
5. endRequest

For our work, we need to handle the initializeRequest only. First make sure that your page contains ScriptManager, UpdatePanel, and UpdateProgress controls.

Now, if you want to keep the existing async postback alive, and kill all new async postbacks that are occuring, then add this script:

<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);

function
InitializeRequest(sender, args) {
if (prm.get_isInAsyncPostBack()) {
args.set_cancel(true);
}
}
</script>

if you want to kill the existing async postback and start the new one, then replace the above function with this one:

function InitializeRequest(sender, args) {
if(prm.get_isInAsyncPostBack(){
prm.abortPostBack();
}
}