Visual Studio xml formatting error “an error occurred loading this property page”

I using VS2008 and got error xml. After that I can’t read web.config (so bad) and go to Option –> Text Editor –> XML –> Formatting got a bad message “an error occurred loading this property page

And Google’s time…. i searched solution for that. Search with keyword “vs 2008 option xml formatting error

To fix this issue need to do:

Step 1: Open cmd “Run –> cmd”

Step 2: Go to the path:

-          VS2005: “C:\Program Files\Microsoft Visual Studio 8\VC\”

-          VS2008: “C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\”

Step 3: Typing magic command:

devenv /setup

Step 4: Wait…wait…it take one or two minutes

Step 5: Open VS again and look the nice result.

How change the view location in MVC? / How to use ViewEngine in MVC?

In my personal project, i got a needs building various layout for each flow .I researched on google and got a solution.

That is customize ViewEngine in MVC. :)

Default ViewLocation is:

~/Views/<controller>/<viewname>.aspx

~/Views/<controller>/<viewname>.ascx

For customize default view engine , created a class inherit WebFormViewEngine. For example i created MyViewEngine

public class MyViewEngine : WebFormViewEngine
{

    public MyViewEngine()
    {
        base.MasterLocationFormats = new string[] {
            "~/Themes/{2}/Views/{1}/{0}.master",
            "~/Themes/{2}/Views/Shared/{0}.master"
        };
        base.ViewLocationFormats = new string[] {
            "~/Themes/{2}/Views/{1}/{0}.aspx",
            "~/Themes/{2}/Views/{1}/{0}.ascx",
            "~/Themes/{2}/Views/Shared/{0}.aspx",
            "~/Themes/{2}/Views/Shared/{0}.ascx"
        };
        base.PartialViewLocationFormats = ViewLocationFormats ;
    }

public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
    {
        //Customize any path for return ViewEngineResult
    }
}

Add customized viewengine to ViewEngines:

protected void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);

    // Replace the Default WebFormViewEngine with our custom WebFormThemeViewEngine
    System.Web.Mvc.ViewEngines.Engines.Clear();
    System.Web.Mvc.ViewEngines.Engines.Add(new MyViewEngine());
}

I will post the sample code soon.

Excel : Search And Replace by VBscript.

Sub Replace()

Application.ScreenUpdating = False
Application.Calculation = xlManual
Dim cell As Range
For Each cell In Intersect(Selection, _
ActiveSheet.UsedRange)
If IsNumeric(cell) = False And Trim(cell) = "." And cell.Row > 1 Then
cell.Value = ""
End If
Next cell
Application.Calculation = xlAutomatic 'xlCalculationAutomatic
Application.ScreenUpdating = False

End Sub

Adding the Macro
1. Copy the macro above pressing the keys CTRL+C
2. Open your workbook
3. Press the keys ALT+F11 to open the Visual Basic Editor
4. Press the keys ALT+I to activate the Insert menu
5. Press M to insert a Standard Module
6. Paste the code by pressing the keys CTRL+V
7. Make any custom changes to the macro if needed at this time
8. Save the Macro by pressing the keys CTRL+S
9. Press the keys ALT+Q to exit the Editor, and return to Excel.

To Run the Macro…
To run the macro from Excel, open the workbook, and press ALT+F8 to display the Run Macro Dialog. Double Click the macro’s name to Run it.

PostgreSQL Tips: Get tablenames and column in database

I have requirement need script. I did it and i share it, hope it’ll useful for someone.

SELECT
t.tablename,
a.attname AS "Column"
--,pg_catalog.format_type (a.atttypid, a.atttypmod) AS "Datatype"
FROM
pg_tables t,
pg_catalog.pg_attribute a
WHERE
a.attnum > 0
AND NOT a.attisdropped
AND a.attrelid = (
SELECT
c.oid
FROM
pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n
ON   n.oid = c.relnamespace
WHERE
c.relname = t.tablename
AND pg_catalog.pg_table_is_visible (c.oid)
)
AND t.tablename NOT LIKE 'pg%'
AND t.tablename NOT LIKE 'sql%'

NHibernate Tips: Updating objects

1. Updating in the same ISession

Transactional persistent instances (ie. objects loaded, saved, created or queried by the ISession) may be manipulated by the application and any changes to persistent state will be persisted when the ISession is flushed (discussed later in this chapter). So the most straightforward way to update the state of an object is to Load() it, and then manipulate it directly, while the ISession is open:

DomesticCat cat = (DomesticCat) sess.Load( typeof(Cat), 69L );
cat.Name = "PK";
sess.Flush();  // changes to cat are automatically detected and persisted

Sometimes this programming model is inefficient since it would require both an SQL SELECT (to load an object) and an SQL UPDATE (to persist its updated state) in the same session. Therefore NHibernate offers an alternate approach.

2. Updating detached objects

Many applications need to retrieve an object in one transaction, send it to the UI layer for manipulation, then save the changes in a new transaction. (Applications that use this kind of approach in a high-concurrency environment usually use versioned data to ensure transaction isolation.) This approach requires a slightly different programming model to the one described in the last section. NHibernate supports this model by providing the method Session.Update().

// in the first session
Cat cat = (Cat) firstSession.Load(typeof(Cat), catId);
Cat potentialMate = new Cat();
firstSession.Save(potentialMate);

// in a higher tier of the application
cat.Mate = potentialMate;

// later, in a new session
secondSession.Update(cat);  // update cat
secondSession.Update(mate); // update mate

If the Cat with identifier catId had already been loaded by secondSession when the application tried to update it, an exception would have been thrown.

The application should individually Update() transient instances reachable from the given transient instance if and only if it wants their state also updated. (Except for lifecycle objects, discussed later.)

Hibernate users have requested a general purpose method that either saves a transient instance by generating a new identifier or update the persistent state associated with its current identifier. The SaveOrUpdate() method now implements this functionality.

NHibernate distinguishes “new” (unsaved) instances from “existing” (saved or loaded in a previous session) instances by the value of their identifier (or version, or timestamp) property. The unsaved-value attribute of the <id> (or <version>, or <timestamp>) mapping specifies which values should be interpreted as representing a “new” instance.

<id name="Id" type="Int64" column="uid" unsaved-value="0">
    <generator class="hilo"/>
</id>

The allowed values of unsaved-value are:

  • any – always save
  • none – always update
  • null – save when identifier is null
  • valid identifier value – save when identifier is null or the given value
  • undefined – if set for version or timestamp, then identifier check is used

If unsaved-value is not specified for a class, NHibernate will attempt to guess it by creating an instance of the class using the no-argument constructor and reading the property value from the instance.

// in the first session
Cat cat = (Cat) firstSession.Load(typeof(Cat), catID);

// in a higher tier of the application
Cat mate = new Cat();
cat.Mate = mate;

// later, in a new session
secondSession.SaveOrUpdate(cat);   // update existing state (cat has a non-null id)
secondSession.SaveOrUpdate(mate);  // save the new instance (mate has a null id)

The usage and semantics of SaveOrUpdate() seems to be confusing for new users. Firstly, so long as you are not trying to use instances from one session in another new session, you should not need to use Update() or SaveOrUpdate(). Some whole applications will never use either of these methods.

Usually Update() or SaveOrUpdate() are used in the following scenario:

  • the application loads an object in the first session
  • the object is passed up to the UI tier
  • some modifications are made to the object
  • the object is passed back down to the business logic tier
  • the application persists these modifications by calling Update() in a second session

SaveOrUpdate() does the following:

  • if the object is already persistent in this session, do nothing
  • if the object has no identifier property, Save() it
  • if the object’s identifier matches the criteria specified by unsaved-value, Save() it
  • if the object is versioned (version or timestamp), then the version will take precedence to identifier check, unless the versions unsaved-value="undefined" (default value)
  • if another object associated with the session has the same identifier, throw an exception

The last case can be avoided by using SaveOrUpdateCopy(Object o). This method copies the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. The method returns the persistent instance. If the given instance is unsaved or does not exist in the database, NHibernate will save it and return it as a newly persistent instance. Otherwise, the given instance does not become associated with the session. In most applications with detached objects, you need both methods, SaveOrUpdate() and SaveOrUpdateCopy().

3. Reattaching detached objects

The Lock() method allows the application to reassociate an unmodified object with a new session.

//just reassociate:
sess.Lock(fritz, LockMode.None);
//do a version check, then reassociate:
sess.Lock(izi, LockMode.Read);
//do a version check, using SELECT ... FOR UPDATE, then reassociate:
sess.Lock(pk, LockMode.Upgrade);

NHibernate Tips: Criteria queries & Queries in native SQL

Criteria queries

HQL is extremely powerful but some people prefer to build queries dynamically, using an object oriented API, rather than embedding strings in their .NET code. For these people, NHibernate provides an intuitive ICriteria query API.

ICriteria crit = session.CreateCriteria(typeof(Cat));
crit.Add( Expression.Eq("color", Eg.Color.Black) );
crit.SetMaxResults(10);
IList cats = crit.List();

If you are uncomfortable with SQL-like syntax, this is perhaps the easiest way to get started with NHibernate. This API is also more extensible than HQL. Applications might provide their own implementations of the ICriterion interface.

Queries in native SQL

You may express a query in SQL, using CreateSQLQuery(). You must enclose SQL aliases in braces.

IList cats = session.CreateSQLQuery(
    "SELECT {cat.*} FROM CAT {cat} WHERE ROWNUM<10",
    "cat",
    typeof(Cat)
).List();
IList cats = session.CreateSQLQuery(
    "SELECT {cat}.ID AS {cat.Id}, {cat}.SEX AS {cat.Sex}, " +
           "{cat}.MATE AS {cat.Mate}, {cat}.SUBCLASS AS {cat.class}, ... " +
    "FROM CAT {cat} WHERE ROWNUM<10",
    "cat",
    typeof(Cat)
).List()

SQL queries may contain named and positional parameters, just like NHibernate queries.

NHibernate Tips: The IQuery interface

If you need to specify bounds upon your result set (the maximum number of rows you want to retrieve and / or the first row you want to retrieve) you should obtain an instance of NHibernate.IQuery:

IQuery q = sess.CreateQuery("from DomesticCat cat");
q.SetFirstResult(20);
q.SetMaxResults(10);
IList cats = q.List();

You may even define a named query in the mapping document. (Remember to use a CDATA section if your query contains characters that could be interpreted as markup.)

<query name="Eg.DomesticCat.by.name.and.minimum.weight"><![CDATA[
    from Eg.DomesticCat as cat
        where cat.Name = ?
        and cat.Weight > ?
] ]></query>
IQuery q = sess.GetNamedQuery("Eg.DomesticCat.by.name.and.minimum.weight");
q.SetString(0, name);
q.SetInt32(1, minWeight);
IList cats = q.List();

The query interface supports the use of named parameters. Named parameters are identifiers of the form :name in the query string. There are methods on IQuery for binding values to named or positional parameters. NHibernate numbers parameters from zero. The advantages of named parameters are:

  • named parameters are insensitive to the order they occur in the query string
  • they may occur multiple times in the same query
  • they are self-documenting
//named parameter (preferred)
IQuery q = sess.CreateQuery("from DomesticCat cat where cat.Name = :name");
q.SetString("name", "Fritz");
IEnumerable cats = q.Enumerable();
//positional parameter
IQuery q = sess.CreateQuery("from DomesticCat cat where cat.Name = ?");
q.SetString(0, "Izi");
IEnumerable cats = q.Enumerable();
//named parameter list
IList names = new ArrayList();
names.Add("Izi");
names.Add("Fritz");
IQuery q = sess.CreateQuery("from DomesticCat cat where cat.Name in (:namesList)");
q.SetParameterList("namesList", names);
IList cats = q.List();

NHibernate Tips : Querying

If you don’t know the identifier(s) of the object(s) you are looking for, use the Find() methods of ISession. NHibernate supports a simple but powerful object oriented query language.

IList cats = sess.Find(
    "from Cat as cat where cat.Birthdate = ?",
    date,
    NHibernateUtil.Date
);

IList mates = sess.Find(
    "select mate from Cat as cat join cat.Mate as mate " +
    "where cat.name = ?",
    name,
    NHibernateUtil.String
);

IList cats = sess.Find( "from Cat as cat where cat.Mate.Birthdate is null" );

IList moreCats = sess.Find(
    "from Cat as cat where " +
    "cat.Name = 'Fritz' or cat.id = ? or cat.id = ?",
    new object[] { id1, id2 },
    new IType[] { NHibernateUtil.Int64, NHibernateUtil.Int64 }
);

IList mates = sess.Find(
    "from Cat as cat where cat.Mate = ?",
    izi,
    NHibernateUtil.Entity(typeof(Cat))
);

IList problems = sess.Find(
    "from GoldFish as fish " +
    "where fish.Birthday > fish.Deceased or fish.Birthday is null"
);

The second argument to Find() accepts an object or array of objects. The third argument accepts a NHibernate type or array of NHibernate types. These given types are used to bind the given objects to the ? query placeholders (which map to input parameters of an ADO.NET IDbCommand). Just as in ADO.NET, you should use this binding mechanism in preference to string manipulation.

The NHibernateUtil class defines a number of static methods and constants, providing access to most of the built-in types, as instances of NHibernate.Type.IType.

If you expect your query to return a very large number of objects, but you don’t expect to use them all, you might get better performance from the Enumerable() methods, which return a System.Collections.IEnumerable. The iterator will load objects on demand, using the identifiers returned by an initial SQL query (n+1 selects total).

// fetch ids
IEnumerable en = sess.Enumerable("from eg.Qux q order by q.Likeliness");
foreach ( Qux qux in en )
{
    // something we couldnt express in the query
    if ( qux.CalculateComplicatedAlgorithm() ) {
        // dont need to process the rest
        break;
    }
}

The Enumerable() method also performs better if you expect that many of the objects are already loaded and cached by the session, or if the query results contain the same objects many times. (When no data is cached or repeated, Find() is almost always faster.) Heres an example of a query that should be called using Enumerable():

IEnumerable en = sess.Enumerable(
    "select customer, product " +
    "from Customer customer, " +
    "Product product " +
    "join customer.Purchases purchase " +
    "where product = purchase.Product"
);

Calling the previous query using Find() would return a very large ADO.NET result set containing the same data many times.

NHibernate queries sometimes return tuples of objects, in which case each tuple is returned as an array:

IEnumerable foosAndBars = sess.Enumerable(
    "select foo, bar from Foo foo, Bar bar " +
    "where bar.Date = foo.Date"
);
foreach (object[] tuple in foosAndBars)
{
    Foo foo = tuple[0]; Bar bar = tuple[1];
    ....
}

C# Tutorial: Get,Set properties for object.

I lazy when do one work every coding, that’s copy DAO to Entity in Hibernate (my company’s framework) please dont ask why do that ^^.

Here is may code:

static void Main(string[] args)
{
User dto = new User();
//dto.ID = new Guid();
dto.FirstName = "Bao";
dto.MiddleName = "Duc Phuc";
dto.LastName = "Nguyen";

UserBE be = new UserBE();
be = ConvertDTOtoBE<User, UserBE>(dto, be) as UserBE;

PropertyInfo[] pi1 = typeof(User).GetProperties();
PropertyInfo[] pi2 = typeof(UserBE).GetProperties();
Console.WriteLine(typeof(User).Name);
foreach (PropertyInfo pi in pi1)
{
Console.WriteLine(pi.Name + " : " + pi.GetValue(dto, null));
}
Console.WriteLine("\n" + typeof(UserBE).Name);
foreach (PropertyInfo pi in pi2)
{
Console.WriteLine(pi.Name + " : " + pi.GetValue(be, null));
}
Console.WriteLine();
}

public static T2 ConvertDTOtoBE<T1, T2>(T1 t1, T2 t2)
where T2:class,new()
{
//T2 t2 = new T2();
t2 = new T2();
Type type1 = typeof(T1);

PropertyInfo[] pi1 = type1.GetProperties();
PropertyInfo[] pi2 = typeof(T2).GetProperties();
PropertyInfo piTmp;
foreach (PropertyInfo pi in pi1)
{
piTmp = pi2.FirstOrDefault(p => p.Name == pi.Name);
if (piTmp != null && piTmp.CanWrite && piTmp.PropertyType.Equals(pi.PropertyType))
{
piTmp.SetValue(t2, pi.GetValue(t1, null),null);
//Console.WriteLine(pi.Name + " : " + pi.GetValue(t1, null));
}
}
return t2;
}

C# Tutorial – Using Reflection to Get Object Information

public class MyObject { //public fields public string myStringField; public int myIntField; public MyObject myObjectField;
//public properties public string MyStringProperty { get; set; } public int MyIntProperty { get; set; } public MyObject MyObjectProperty { get; set; } //public events public event EventHandler MyEvent1; public event EventHandler MyEvent2; }

To get a list of public fields in an object, we’ll use Type’s GetField method:

Type myObjectType = typeof(MyObject);
System.Reflection.FieldInfo[] fieldInfo = myObjectType.GetFields(); foreach (System.Reflection.FieldInfo info in fieldInfo) Console.WriteLine(info.Name); // Output: // myStringField // myIntField // myObjectField

An important thing to note here is that the fields are not guaranteed to come out in any particular order. If you use GetFields, you should never depend on the order being consistent. The FieldInfo class that gets returned actually contains a lot of useful information. It also contains the ability to set that field on an instance of MyObject – that’s where the real power comes in.

MyObject myObjectInstance = new MyObject();
foreach (System.Reflection.FieldInfo info in fieldInfo) { switch (info.Name) { case "myStringField": info.SetValue(myObjectInstance, "string value"); break; case "myIntField": info.SetValue(myObjectInstance, 42); break; case "myObjectField": info.SetValue(myObjectInstance, myObjectInstance); break; } } //read back the field information foreach (System.Reflection.FieldInfo info in fieldInfo) { Console.WriteLine(info.Name + ": " + info.GetValue(myObjectInstance).ToString()); } // Output: // myStringField: string value // myIntField: 42 // myObjectField: MyObject

Combining this ability with the ability to create custom attributes provides a framework on which almost any serialization technique can be built.

Properties and events are retrieved almost identically to fields:

Type myObjectType = typeof(MyObject);
//Get public properties System.Reflection.PropertyInfo[] propertyInfo = myObjectType.GetProperties(); foreach (System.Reflection.PropertyInfo info in propertyInfo) Console.WriteLine(info.Name); // Output: // MyStringProperty // MyIntProperty // MyObjectProperty //Get events System.Reflection.EventInfo[] eventInfo = myObjectType.GetEvents(); foreach (System.Reflection.EventInfo info in eventInfo) Console.WriteLine(info.Name); // Output: // MyEvent1 // MyEvent2
Follow

Get every new post delivered to your Inbox.