asp.net input filtering using validation controls
1. only alphabets & max 5 char FILTER
<asp:RegularExpressionValidator ID="regexTextBox1"
ControlToValidate="txt1" runat="server"
ValidationExpression="^[a-zA-Z]{0,5}$" Text="only alphabets & max 5 char" />
2. only numeric & max 5 char FILTER
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
ControlToValidate="txt2" runat="server"
ValidationExpression="^[\d]{0,5}$" Text="only numeric & max 5 char" />
3. only alpha-numeric & max 5 char FILTER
<asp:RegularExpressionValidator ID="RegularExpressionValidator2"
ControlToValidate="txt3" runat="server"
ValidationExpression="^[0-9a-zA-Z' ']{0,5}$" Text="alpha numeric & 5 char long" />
Creating Transaction by using System.Transactionscope
/* Using System.Transaction object */
string cn = ConfigurationManager.ConnectionStrings["universityConnectionString1"].ToString();
using (TransactionScope ts = new TransactionScope())
{
using (SqlConnection cns = new SqlConnection())
{
cns.ConnectionString = cn;
cns.Open();
using (SqlCommand cmd = cns.CreateCommand())
{
try
{
cmd.CommandText = "Insert into creditAccount(Amount)values(" + int.Parse(txtcreditamt.Text) + ")";
cmd.ExecuteScalar();
int x = int.Parse(txtdebitamt.Text);
cmd.CommandText = "Insert into debitAccount(Amount)values(" + int.Parse(txtcreditamt.Text) + ")";
cmd.ExecuteScalar();
ts.Complete();
ts.Dispose();
}
catch (Exception)
{
}
}
}
}
Creating a transaction by using ADO.NET dbTransaction object
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString = ConfigurationManager.ConnectionStrings["universityConnectionString1"].ToString();
cn.Open();
using (SqlTransaction tran = cn.BeginTransaction())
{
try
{
using (SqlCommand cmd = cn.CreateCommand())
{
cmd.Transaction = tran;
cmd.CommandText = "Insert into creditAccount(Amount)values(" + int.Parse(txtcreditamt.Text) + ")";
cmd.ExecuteScalar();
int x = int.Parse(txtdebitamt.Text);
cmd.CommandText = "Insert into debitAccount(Amount)values(" + int.Parse(txtcreditamt.Text) + ")";
cmd.ExecuteScalar();
}
tran.Commit();
}
catch (Exception)
{
tran.Rollback();
}
}
}
Wizard Control with Update Panel – Scroll page to top on next button
When you use ASP.NET Update panel things become little complicated. To scroll the page on top when user hit next button in wizard control try this script
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
if (sender._postBackSettings.sourceElement.defaultValue != "") {
if (sender._postBackSettings.sourceElement.defaultValue != undefined) {
scrollTo(0, 0);
}
}
}
</script>
Easy reading is damn hard writing.
ASP.NET Find page control
public static Control findcontrol(Page p)
{
foreach (Control masterControl in p.Controls)
{
if (masterControl is MasterPage)
{
foreach (Control formControl in masterControl.Controls)
{
if (formControl is System.Web.UI.HtmlControls.HtmlForm)
{
foreach (Control contentControl in formControl.Controls)
{
if (contentControl is ContentPlaceHolder)
{
foreach (Control childControl in contentControl.Controls)
{
if (childControl is TreeView)
{
return childControl;
}
}
}
}
}
}
}
}
return null;
}
C# datetime Find Second Monday and Find Fourth Monday
Suppose you have some scheduled job which must not run on Second Monday and Fourth Monday of the month, the following code spinet will be helpful to identify the date-
private int GetDateForWeekDay(DayOfWeek DesiredDay, int Occurrence, int Month, int Year)
{
DateTime dtSat = new DateTime(Year, Month, 1);
int j = 0;
if (Convert.ToInt32(DesiredDay) - Convert.ToInt32(dtSat.DayOfWeek) >= 0)
j = Convert.ToInt32(DesiredDay) - Convert.ToInt32(dtSat.DayOfWeek) + 1;
else
j = (7 - Convert.ToInt32(dtSat.DayOfWeek)) + (Convert.ToInt32(DesiredDay) + 1);
return j + (Occurrence - 1) * 7;
}
Sharepoint 2010 & Silverlight ListData.svc WCF Service : System.Security.SecurityException
If you come across Security Exception in your silverlight application while consuming WCF service, one thing worth checking is existence of “crossdomain.xml” and “clientaccesspolicy.xml” files on your (Sharepoint) IIS web application’s root directory.
Below is my silverlight application code to call listdata.svc on a different SharePoint server:
private MyServiceReference.APMSDataContext _context = new APMSDataContext(new Uri("http://sptest:1800/_vti_bin/listdata.svc"));
public void GetTasksByUser(string sUser)
{
_context.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
var query = (DataServiceQuery<ProjectTasksItem>)_context.ProjectTasks.AddQueryOption("Select", "Id,Title");
query.BeginExecute(DisplayTasks, query);
}
private void DisplayTasks(IAsyncResult result)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
try
{
DataServiceQuery<ProjectTasksItem> query = (DataServiceQuery<ProjectTasksItem>)result.AsyncState;
var TasksQuery = query.EndExecute(result);
foreach (var x in TasksQuery)
{
string sTaskTitle = x.Title;
}
}
catch (Exception ex)
{
string s = ex.Message.ToString();
}
});
}
Here is the standard clientaccesspolicy file
<?xml version="1.0" encoding="utf-8"?> <access-policy> <cross-domain-access> <policy> <allow-from http-request-headers="*"> <domain uri="*"/> </allow-from> <grant-to> <resource path="/" include-subpaths="true"/> </grant-to> </policy> </cross-domain-access> </access-policy>
And here is CrossDomain file
<?xml version="1.0"?> <!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd"> <cross-domain-policy> <allow-http-request-headers-from domain="*" headers="*"/> </cross-domain-policy>
And here the Architecture diagram of my solution
sharepoint 2010 The Web application at http://localhost could not be found
I was writing C# console application as SharePoint Isolated Programming style and got the following error on the very first line:
The reason for this error was – I was running console application targeting for x86 – as you can see in the next screenshot.
Since Shareponit 2010 is now only 64 bit, you need to change your target framework to x64.
1. Select the Project – > Right Click -> Properties
2. Select Build tab
3. Select x64 in Platform target dropdown
Sharepoint 2010 – get user full name using web service
Use following web service if you wants to get various information about the user.
http://localhost/_vti_bin/UserGroup.asmx
If you do not want to reference sharepoint object model in your visual studio project, you can certainly use UserGroup web service to get the user full name –
public static string GetCurrentUserName()
{
SPUserGroup.UserGroup ug = new SPUserGroup.UserGroup();
ug.Credentials = System.Net.CredentialCache.DefaultCredentials;
var xuser = ug.GetCurrentUserInfo();
return xuser.FirstChild.Attributes["Name"].Value;
}
Practical Example – Agile Methodology
Here is a simple analogy to help you envision this process. You go to the mall on a serious shopping
spree and fill up your car with boxes, bags, and packages of all shapes and sizes. You arrive home and are
faced with the task of bringing everything into the house. You quickly realize that you can’t carry
everything in one trip, so you start planning the loads. Perhaps on the first trip you bring in the box of ice
cream that’s starting to melt. On the next trip you carry the big heavy box. On subsequent trips you carry
several lighter-weight items. As the car begins to empty, you find yourself figuring how many loads are
left.
You just applied the agile methodology to manage the project of unloading the car. The things you
brought in are the user stories, and each trip represents an iteration. You can only carry a certain
amount with each trip so at the beginning of the each trip you review what is left and plan the next load.
You can estimate how many trips (iterations) you’ll need, which will give you a good idea of when you’ll
be done.



leave a comment