Business and Technology Consulting Organization in Mumbai

Electronic Transformation Globally Technology Solution IT Consultancy Service Provider

How to read wordpress feed into asp.net application

enum to list in csharp
This function will convert any enum to a List object

public class EnumHelper
{
/// <  summary >
/// Convert enum to a list object.
/// <  /summary >
/// <  typeparam name="T" ><  /typeparam >
/// <  returns ><  /returns >
public static List<  T > EnumToList<  T >()
{
	Type enumType = typeof(T);

	// You can't use type constraints on value types, so have to check & throw error.
	if (enumType.BaseType != typeof(Enum))
		throw new ArgumentException("T must be of type System.Enum type");

	Array enumValArray = Enum.GetValues(enumType);

	List<  T > enumValList = new List<  T >(enumValArray.Length);

	foreach (int val in enumValArray)
	{
		enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
	}

	return enumValList;
}

// Now call the function with enum you want to conver into a list  EnumHelper.EnumToList< EventState >()

public static List < EventState > GetEventStates()
{
	List< EventState > eventStates = EnumHelper.EnumToList< EventState >();
		//.FindAll(
		//delegate(EventState x)
		//{
		//    return x != EventState.Cancelled  ;
		//});
	return eventStates;
}

Stop subsequent submit button clicks when a earlier request is being processed in ASP.NET

How we can stop the subsequent click when a earlier request is still been processed.

here is the javascript code you need to place above your update panel.
< script type=”text/javascript” language=”javascript” >
        var requestManager = Sys.WebForms.PageRequestManager.getInstance();
        requestManager.add_initializeRequest(StopPostbackOnSubsequentSubmitClicks);

        function StopPostbackOnSubsequentSubmitClicks(sender, args) {
            if (requestManager.get_isInAsyncPostBack() &
  args.get_postBackElement().id == ‘<%=btnSubmit.ClientID %>’)
            {
                args.set_cancel(true);               
                alert(‘Please wait, earlier request is still being processed’);
            }
        }
    < /script >

Now write your update panel code
  < asp:UpdatePanel runat=”server” ID=”upnlLogin” UpdateMode=”Conditional” >
            < ContentTemplate >
               
  // do whatever you need

  < asp:Button ID=”btnSubmit” runat=”server” Text=”Sign in” CssClass=”button” OnClick=”btnSubmit_Click” />
                           
            < /ContentTemplate>
           
        < /asp:UpdatePanel>
        < asp:UpdateProgress AssociatedUpdatePanelID=”upnlLogin” runat=”server” >
            < ProgressTemplate>
                < img src=”../Images/spinner.gif” / >
            < /ProgressTemplate >
        < /asp:UpdateProgress >

// Now see the code behind implementation

protected void btnSubmit_Click(object sender, EventArgs e)
        {

            Thread.Sleep(1000); 
 }


how to find application root dynamically in asp.net

sometimes you might have experienced some of the images are not appearing on your web page because of inappropriate path. so you need to know the root of the application dynically, because that keep chaning from development server to testing server, testing server to production server.

so you just need to do the following.

public static string ApplicationRoot
{
get
{
string root = null;
if (HttpContext.Current.Request.ApplicationPath != “/”)
root = HttpContext.Current.Request.Url.GetLeftPart(System.UriPartial.Authority) + “/” + HttpContext.Current.Request.ApplicationPath;
else
root = HttpContext.Current.Request.Url.GetLeftPart(System.UriPartial.Authority) + “/”;

if (!root.EndsWith(“/”))
root += “/”;

return root;
}
}

now whenever you are adding some image in any usercontrol, and you want to make sure the image is appearing allover the places then just use the following code

< img src=’< %=ApplicationRoot +”Images/myImage.jpg”% >’ >


How to use Extention Method to JSON string

Extension method allows you to add new method to the existing class without modifying the code, recompiling or modifying the original code.

public static class ExtensionsMethods
{

public static string Reverse(this string content)
{
char[] charArray = new char[content.Length];
int len = content.Length – 1;
for (int i = 0; i <= len; i++)
{
charArray[i] = content[len - i];
}
return new string(charArray);
}

/*Now suppose you want to have some functionality ToJason from all your custom object, you dont have to modify the source code, in the extention method class you just need to add the following line.*/

public static string ToJASON(this object myObject)
{

// you need reference of System.Web.Script.Serialization;
JavaScriptSerializer js = new JavaScriptSerializer();

return js.Serialize(myObject);
}
}

Now lets look at how to use the method

Suppose you have a object called Client

Client client = new Client();
client.Address = “Client’s House”;
client.ClientCode = “000C123″;
client.ClientId = 98;
client.ClientName = “Client the God”;
client.Email = “ac@gmail.com”;

string jsonClient = client.ToJASON();
Response.Write(jsonClient);

the json out put will be :

{“ClientId”:98,”ClientName”:”Client the God”,”ClientCode”:”000C123″,”ClientType”:null,”Organization”:null,”ContactPerson”:null,”Phone”:null,”Email”:”ac@gmail.com”,”Address”:”Client\u0027s House”}

// now get a list of client. and make a jasonstring.
string jsonClients = MasterDTO.GetClients().ToJASON() ;
Response.Write(jsonClients);

the output will be
“}[{"ClientId":0,"ClientName":" Client - 0","ClientCode":"0010","ClientType":null,"Organization":null,"ContactPerson":null,"Phone":" 0Client - 0","Email":" 0Client0@gmail.com","Address":null},{"ClientId":1,"ClientName":" Client - 1","ClientCode":"0011","ClientType":null,"Organization":null,"ContactPerson":null,"Phone":" 1Client - 1","Email":" 1Client1@gmail.com","Address":null},{"ClientId":2,"ClientName":" Client - 2","ClientCode":"0012","ClientType":null,"Organization":null,"ContactPerson":null,"Phone":" 2Client - 2","Email":" 2Client2@gmail.com","Address":null},{"ClientId":3,"ClientName":" Client - 3","ClientCode":"0013","ClientType":null,"Organization":null,"ContactPerson":null,"Phone":" 3Client - 3","Email":" 3Client3@gmail.com","Address":null},{"ClientId":4,"ClientName":" Client - 4","ClientCode":"0014","ClientType":null,"Organization":null,"ContactPerson":null,"Phone":" 4Client - 4","Email":" 4Client4@gmail.com","Address":null},{"ClientId":5,"ClientName":" Client - 5","ClientCode":"0015","ClientType":null,"Organization":null,"ContactPerson":null,"Phone":" 5Client - 5","Email":" 5Client5@gmail.com","Address":null},{"ClientId":6,"ClientName":" Client - 6","ClientCode":"0016","ClientType":null,"Organization":null,"ContactPerson":null,"Phone":" 6Client - 6","Email":" 6Client6@gmail.com","Address":null},{"ClientId":7,"ClientName":" Client - 7","ClientCode":"0017","ClientType":null,"Organization":null,"ContactPerson":null,"Phone":" 7Client - 7","Email":" 7Client7@gmail.com","Address":null},{"ClientId":8,"ClientName":" Client - 8","ClientCode":"0018","ClientType":null,"Organization":null,"ContactPerson":null,"Phone":" 8Client - 8","Email":" 8Client8@gmail.com","Address":null},{"ClientId":9,"ClientName":" Client - 9","ClientCode":"0019","ClientType":null,"Organization":null,"ContactPerson":null,"Phone":" 9Client - 9","Email":" 9Client9@gmail.com","Address":null},{"ClientId":10,"ClientName":" Client - 10","ClientCode":"00110","ClientType":null,"Organization":null,"ContactPerson":null,"Phone":" 10Client - 10","Email":" 10Client10@gmail.com","Address":null}]

Similarly you also can convert the JSON string back to an object form by using the following extention method.

public static object JASONToObject(this string myObjectString)
{
JavaScriptSerializer js = new JavaScriptSerializer();

return js.DeserializeObject(myObjectString);
}


write join using lambada expression

Int64 productInfoId = 0;
using (var etgEntities = new DBETNetEntities())
{

var result = from profile in etgEntities.TbUserProfile
join product in etgEntities.tbProductInfo
on profile.UserInfoID equals product.UserInfoID
where profile.UserProfileID == userProfileId
select product;

productInfoId = result.FirstOrDefault().ProductInfoId;
}
return productInfoId;


Read data using DbDataReader Storeprocedure in Entityframework

How to use  store procedure outputparameter with Entity Framework?

Read data using DbDataReader Storeprocedure in Entityframework, we also see how to deal with Output parameter.

required namespace
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Data.SqlClient;
using System.Linq;

now look at the implementation, its very simple and saves lots of time.

public List SearchProduct1(string SearchText, string SearchBy, string Area, string countryId, int startRowIndex, int maximumRows, ref int TotalRows)
{
List< myProductInfo > objLst = new List< myProductInfo >();
int? _startRowIndex = startRowIndex;
int? _maximumRows = maximumRows;
int? _TotalRows = TotalRows;
int? _contryId = countryId == “” ? 0 : Convert.ToInt32(countryId);

try
{
using (var myEntities = new ApplicationEntities())
{
// this is how you can set the output parameter.
ObjectParameter param = new ObjectParameter(“TotalRows”, typeof(int));

/* here you probably wondering where the “SearchProduct” function come from, well open your edmx file and right click => import function, now select the sp you want to execute, then write the function name as your business need (ex. SearchProduct)
*/
objLst = myEntities.SearchProduct(SearchText, SearchBy, Area, _contryId, _startRowIndex, _maximumRows, param).ToList< myProductInfo >();

 TotalRows = Convert.ToInt32(pTotalRows.Value);
}
}

catch (Exception ex)
{
this.Status = ex.ToString();
}

return objLst;
}


Entity Framework example

You need to install sp1 before you can start with entity framework

If you can’t see the framework template, do the following step
Click on Tools => Option => Projects & Solutions ..then
Click on “User item template location” browse button and set the right path
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\
do same for project templets
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ProjectTemplates\
Now click on “ok”
then close the studio and re-open again ..now you will be able to see the entity framework template

some more guide step – by step can be seen on http://www.installationwiki.org/Installing_ADO.NET_Entity_Framework

Getting problem in Connectionstring in Entity framework ?

< add name=”HRRPMSContext” providerName=”System.Data.EntityClient” connectionString=”metadata=res://ETG.Base.Applications.EntityFramework,Culture=neutral,PublicKeyToken=null/HRRPMSContext.csdl|res://ETG.Base.Applications.EntityFramework,Culture=neutral,PublicKeyToken=null/HRRPMSContext.ssdl|res://ETG.Base.Applications.EntityFramework,Culture=neutral,PublicKeyToken=null/HRRPMSContext.msl;provider=System.Data.SqlClient;provider connection string=’Data Source=ETG1\SQLEXPRESS;;Initial Catalog=ACSampleDB;User ID=HRRPMS;Password=pass;Integrated Security=True;multipleactiveresultsets=true’”/ >

In the above string ETG.Base.Applications.EntityFramework is my assembly name ETG.Base.Applications.EntityFramework.dll

Fetching a collection using entity framework.
public static List< tbCandidate> GetAllCandidates()
{
List< tbCandidate > candidates = new List< tbCandidate>(); ;

using (var hrEntities = new HRRPMSContext())
{
foreach (var candidate in hrEntities.tbCandidate)
{
candidates.Add(candidate);
}
}

return candidates;

}

Adding data example :
public static void SetData()
{
tbCandidate candidate = new tbCandidate();
candidate.Name = “Arindam Chakraborty”;
candidate.Phone = “11545645656″;
candidate.Qualification = “B.Sc”;
candidate.Street = “New Golden Nest”;
Add(candidate);

}

public static void Add(tbCandidate obj)
{
using (var hrEntities = new HRRPMSContext())
{
hrEntities.AddTotbCandidate(obj);
hrEntities.SaveChanges();
}
}

Find a candidate by name from database
public static tbCandidate FindCndidateByName(string name)
{
tbCandidate candidate = null;

using (var hrEntities = new HRRPMSContext())
{
candidate = hrEntities.tbCandidate.FirstOrDefault(c => c.Name == name);
}

return candidate;

}

Update a candidate information

public static void Update(tbCandidate updatedCandidate)
{

using (var hrEntities = new HRRPMSContext())
{
tbCandidate candidate = hrEntities.tbCandidate.FirstOrDefault(c => c.CandidateID == updatedCandidate.CandidateID);
candidate = updatedCandidate;
hrEntities.tbCandidate.Context.ApplyPropertyChanges(“tbCandidate”, candidate);
hrEntities.tbCandidate.Context.SaveChanges();
}
}

Add Data in many tables with transaction scope
public static void AddMultipleRecord(tbInterview interview, tbRequirement requirement)
{

using (TransactionScope scope = new TransactionScope())
{
using (var hrEntities = new HRRPMSContext())
{

hrEntities.AddTotbInterview(interview);
hrEntities.AddTotbRequirement(requirement);

hrEntities.SaveChanges();
scope.Complete();
}
}
}


FirstCoder, a utility for C# developer

Introdcuing an Utility that can reduce your work load specially if you are working in asp.net C#, Just connect your database ..and a few clicks all your business objects are ready to be used.

I have seen at least 40% of our time we spend in doing few standard functions for all the application we develop in our lifetime, sometimes I feel tired doing same monotonous task,  i don’t believe in doing any job which can be automated, let the utility do all task for you….just relax!

I am sure many of you might have experienced the same.  

Here I have identified few tasks for the same reason, and automated for all the following task for you.

Java Script Objects: The utility writes java script for all your business objects with few standard methods in it, like addToList(), removeFromList(), getById(id),  getAll(),

JSON: The utility writes Json structure for all your business objects with few standard methods in it. Like Save, Get. I keep the JSON structure ready, you just need to set the value from your page control and you are done! JSON can make call to web service or WCF service.

WCF / Web Service:  The utility creates wcf service for your entire object with a hosting plan on IIS and one page for service registration.

HBM: The utility gets your entire basic HBM ready within in a minute; I take care of id, composite key, one to many, one to one etc.

Business Entity: Write all business entity with custom attribute like wcf compatible, n-hibernate compatible.

Data Objects Structure: You must have seen often we change our database object structure during the development, but never update our technical specification, so here the utility create a document for all tables, views & procedures. 

Once you standardize the definition, the utility  produce exactly the same, you don’t have to spend time in object creation & to review them, and thus the utility also save some time, so more quickly you can concentrate on core business area.

Here is the link to download the utility

Upcoming Features :
1. Format all projects code at one click.
2. Identify all areas where function definition has not been written
3. Generate a report all of all function details, so we can identify if any duplicate function written or naming convention are incorrect, that may help to save the review time.


edit data in dataset finally save in database

I was just thinking of sharing the this peice of code, nothing much simply editing data in dataset and finally submitting in data in database, also addressing the  concurrency problem inmy next article .. direct implementation ..take a look at url below.

 http://www.etgconsultancy.com/AspNetControls/Edit-gridview-save-dataset-to-database.aspx


Journery started with LAMP

I did php development for only a few months, 6 years back. After that i never got a chance to look at php further, during that small development experience i realised that i can make a long & healthy journey with php. But somewhow that didn’t happen, rather i have made my journey with .net framework.. so far journey was not bad.

But now i have got the chance to taste the old essence again, this time I really don’t want to miss the opportunity. I wish to look at php more passionately. I will keep posting my php journey on http://etgconsultancy.com/Php . Very soon i write on php jquery, php ajax, php oops, how to deal with customobject in php, php with xml …any many more to talk about.

Nowdays many small companies, web start ups and web designers that don’t have any PHP programming experience, most of these people need to hire a full time programmer. They need some programming done, for a short amount of time. ETG Consultancy help them to achive their goal.

We have a team of experienced, reliable and professional php developer,  We work remotely on your project until it is completed to your specifications. We are always available for ongoing support after a project is finished. You can count on us to get your project completed.

Whatever PHP programming you need, I can accomodate you. Contact me to discuss your project. Build your business site or personal website in PHP MySQL

Conatct me for your quick solution on http://etgconsultancy.com

Arindam Chakraborty


Sponsored by

HR Recruitment & Process Management System
Jewellery production process management software
Share
©2009 ETG Consultancy, All Rights Reserved Privacy Policy | Terms & Conditions
Asp.net, Ado.net, .Net Remoting, .Net Webservice, SQL, XML, XSLT, WCF, WPF, WWF NHibernate, Ajax, Jquery, DHTML