Programming: May 2009

Monday, May 4, 2009

Attach multiple functions to events

Attach multiple functions to events

Attach multiple functions to events

The function that need to place some wear on page:

function addEvent(obj, evType, fn)
{
if (obj.addEventListener)
{
obj.addEventListener(evType, fn, false);
return true;
}
else if (obj.attachEvent)
{
var r = obj.attachEvent("on"+evType, fn);
return r;
}
else
{
return false;
}
}

Sample to call the function:

addEvent(window, 'load', functionName);

.NET Internationalization with databa...

NET Internationalization with database resource provider and custom cultures

.NET Internationalization with database resource provider and custom cultures

Database storage is a popular option for Web-application resources, for a number of reasons. You can probably guess, at some point with a site that has thousands of pages and multiple-thousand resource entries, using assembly resources might not be ideal. It will add to run-time memory usage, not to mention the increased number of assemblies loaded into the application domain. Both of these results can have a negative impact on performance for extremely large sites, making the latency of a database call worthwhile. Database resources might also provide a more flexible and manageable environment for the localization process, for reducing duplicates, for intricate caching options, and for storing possibly larger blocks of content. Lastly, allocating resources to a database makes it possible to support more complicated hierarchies of translated content, where customers or departments might have customized versions of the text that is then also localized.

PS: Articles with information about:
Hooking meta:Resource parsing in ASP.NET 2.0? by Rick Strahl
Extending the ASP.NET 2.0 Resource-Provider Model by Michèle Leroux Bustamante
.NET Internationalization: Using Custom Cultures

Small things about .NET

Small things about .NET

Small things about .NET

Sometimes I need to build string from strings array spparated by any simbol, so I found this sample:

string[] strArr = {"1","2","3"};
string output = "";

for(int i = 0; i < strArr.Leght;)
output += strArr[i] + ((strArr.Leght > ++i) ? "," : "");


Result: 1,2,3

Checking site status

Checking site status

Checking site status

For this blog I need the image that link to my private web site, but my web site not all time on line so I write javascript that show if my web site on line, and if no so write "My site off line.." become image.

<a id="myWebsiteImgLink" href="http://panshin.no-ip.org">

<img src="http://panshin.no-ip.org/Images/WebsiteImg.jpg" onerror="OnErrorLoadImage(this);"/>

</a>

<script>

function OnErrorLoadImage(img)

{

    document.getElementById('myWebsiteImgLink').href = '#';

    document.getElementById('myWebsiteImgLink').innerHTML = '<strong>My Web Site is Offline Now.</strong>';

}

 

</script>


Simple questions in job interview for...

Simple questions in job interview for software engineer

Simple questions in job interview for software engineer


  • Authentication - Windows Form,Passport,None
  • Authorization - is the concept of allowing access to resources only to those permitted to use them.
  • Virtual constructor - A constructor cannot be virtual because at the time when the constructor is invoked the virtual table would not be available in the memory. Hence we cannot have a virtual constructor. But we have pattern for create Virtual constructor. It should be possible to create different type of objects depending on a given object. The Virtual Constructor pattern is also called Factory.
  • Virtual destructor - A virtual destructor is one that is declared as virtual in the base class and is used to ensure that detractors are called in the proper order. It is to be remembered that detractors are called in the reverse order of inheritance. If a base class pointer points to a derived class object and we some time later use the delete operator to delete the object, then the derived class detractor is not called.
  • Context switch - is the computing process of storing and restoring the state of CPU such that multiple processes can share a single CPU resource.
  • Virtual machine - Another meaning of virtual machine is a piece of computer software that isolates the application being used by the user from the computer. Because versions of the virtual machine are written for various computer platforms, any application written for the virtual machine can be operated on any of the platforms, instead of having to produce separate versions of the application for each computer and operating system.
  • Page fault - When a program tries to access some address that is not currently in physical RAM, it generates an interrupt, called Page Fault. This asks the system to retrieve the 4KB page containing the address from page file.
  • Priority inversion - Is the scenario where a low priority task holds a shared resource that is required by a high priority task.
  • Cache coherency - refers to the integrity of data stored in local caches of a shared resource.
  • Design patterns:
    1. Abstract factory - provides a way to encapsulate a group of individual factories that have a common theme.
    2. Adapter - Преобразует интерфейс класса в другой интерфейс, ожидаемый клиентами. Адаптер позволяет классам с несовместимыми интерфейсами работать вместе.
    3. Bridge - Отцепляет абстракцию от ее реализации так, чтобы они могли изменяться независимо.
    4. Builder - Отделяет коструирование сложного Объекта от его представления, позволяя использовать один и тотже Процесс конструирования для создания Различных представлений.
    5. Chain of Responsibility -
    6. Command -
    7. Composite -
    8. Decorator -
    9. Facade -
    10. Factory Method -
    11. Flyweight -
    12. Interpreter -
    13. Iterator -
    14. Mediator -
    15. Memento -
    16. Observer -
    17. Prototype -
    18. Proxy -
    19. Singleton - Гарантирует,что некий класс иметь только один экземпляр, и предоставляет Глобалную точку доступа.
    20. State -
    21. Strategy -
    22. Template Method -
    23. Visitor -
  • BL - business logic
  • DAL - Data access laer
  • Store Procedure - Скорость, Секюрити
  • Reflection - allows an application to discover information about itself. Used for calling methods at run time, or create new data types at run time.
  • OOP - Include three parts:
    1. Abstraction - выделяет существенные характеристики Некторого объекта,отличающие его От всех других объектов.
    2. Polymorphism - Явление при котором Все класы потомки имеют общий Интерфейс. Это позволяет обробатывать объекты класов- потомков как однотипные объекты.
    3. Encapsulation - Представление класса Как черный ящик - пользовател должен видеть только его интерфейс и не Вникать во внутреннюю реализацию.
  • IL (intermediate language) - where a compiler first translate the source code of program into a form more suitable for code-improving transformation, as as an intermediate step before generating object or machine code for a target machine.
  • Datarepeater - repeat controls
  • Datareader - to retrieve a read-only stream ,forward-only stream of data from database.
  • Remoting - .NET Remoting is an enabler for application communication. It is a generic system for different applications to use to communicate with one another. .NET objects are exposed to remote processes, thus allowing interprocess communication. The applications can be located on the same computer, different computers on the same network, or even computers across separate networks..
  • IDispatch - interface exposes objects, Methods and properties to programming Tools and other applications that support. Automation. To access to COM.
  • Difference via classes and structs in C++ - The difference in default access. By default ,all the members of a struct are public Whereas in a class, all the members are Private.
  • Thread - are way for program to split Itself into two or more simultaneously Running tasks.
  • Process
  • Thread and Process - Process carry Considerable state information, have Separate address spaces, and interact Only though system-provided inter-process Communication mechanisms. Multiple Threads, on other hand, typically share the state inf
  • Array.Rank Property - The rank (number of dimensions) of the Array
  • const vs. readonly - A quick synopsis on the differences between 'const' and 'readonly' in C#:
    'const':
    * Can't be static.
    * Value is evaluated at compile time.
    * Initiailized at declaration only.

    'readonly':
    * Can be either instance-level or static.
    * Value is evaluated at run time.
    * Can be initialized in declaration or by code in the constructor.
  • Boxing And Unboxing - Converting a value type to reference type is called Boxing.Unboxing is an explicit operation.
  • Ways to deploy assembly - By Regsvr32,Regasm or MSI.
  • Is xml case sensitive? - Yes.
  • Sealed Classes And Methods In C# - The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class. A sealed class cannot also be an abstract class.

Some links to sites with questions:
http://www.justinangel.net/CommentView,guid,2baecf20-d734-4571-bb5a-fb3c16ccfcd7.aspx
http://www.jobiq.co.il/work-in-csharp-1/
http://www.daquiz.com/interviews_topic.php?cat_id=1&cat_name=.Net
http://community.livejournal.com/rabota_il/profile

Job Interview: .NET Design Patterns q...

Job Interview: .NET Design Patterns questions

Job Interview: .NET Design Patterns questions


Design pattern is a general reusable solution to a commonly occurring problem in software design.

Most popular design patterns:

  • Singleton - is a design pattern that is used to restrict instantiation of a class to one object.
  • Abstract Factory - Abstract Factory is commonly known as factory pattern. In this pattern all the classes involved implement/realize the same interface and the compiler only knows that the created object implements the specific interface but not the object's type. This is very flexible when you need to make a creation decision at runtime depending on some aspect of object's behavior rather than it's type.
  • Adapter Pattern - By converting the interface of one class into another interface which is expected by the clients we can make incompatible classes work together and this is the adapter pattern.
Sources:
www.dotnetheaven.com

Job Interview: .NET OOP questions

Job Interview: .NET OOP questions

Job Interview: .NET OOP questions


I tried to collect here most popular question about OOP from some sites around internet.

What is OOP?
Object Oriented Programming - is a programming paradigm that uses "objects" and their interactions to design applications and computer programs. Is one of the most popular methodologies in software development. It offers a powerful model for creating computer programs. It speeds the program development process, improves maintenance and enhances re usability of programs.

What is object?
An object is a combination of messages and data. Objects can receive and send messages and use messages to interact with each other. The messages contain information that is to be passed to the recipient object.

What is the syntax to inherit from a class in C#?
Place a colon and then the name of the base class.
Example: class MyNewClass : MyBaseClass

Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its super classes.

Does exist Virtual Constructor?
Constructor cannot be virtual because at the time when the constructor is invoked the virtual table would not be available in the memory. Hence we cannot have a virtual constructor. But we have pattern for create Virtual constructor. It should be possible to create different type of objects depending on a given object. The Virtual Constructor pattern is also called Factory.

What is Virtual destructor?
A virtual destructor is one that is declared as virtual in the base class and is used to ensure that detractors are called in the proper order. It is to be remembered that detractors are called in the reverse order of inheritance. If a base class pointer points to a derived class object and we some time later use the delete operator to delete the object, then the derived class detractor is not called.

Can you prevent your class from being inherited by another class?
Yes. The keyword “sealed” will prevent the class from being inherited.

Can you allow a class to be inherited, but prevent the method from being over-ridden?
Yes. Just leave the class public and make the method sealed.

What’s an abstract class?
A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation.

When do you absolutely have to declare a class as abstract?
1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.
2. When at least one of the methods in the class is abstract.

What is an interface class?
Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.

Why can’t you specify the accessibility modifier for methods inside the interface?
They all must be public, and are therefore public by default.

Can you inherit multiple interfaces?
Yes. .NET does support inherit multiple interfaces.

Can you inherit multiple classes?
Not. .NET doesn't support inherit multiple classes.

What happens if you inherit multiple interfaces and they have conflicting method names?
It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.

What’s the difference between an interface and abstract class?
In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers.

What is the difference between a Struct and a Class?
Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another difference is that structs cannot inherit.

Some another subjects for interview:
High transaction Websites



Sources:
www.interviewquestion.us
placementpapers.net
www.coders2020.com


Sunday, May 3, 2009

Create site with Blogger as CMS and P...

Create site

Create site with Blogger as CMS and Picasa as Photoalbum


One day I decide to create my personal site: http://panshin.blogspot.com . I didn't want something difficult. I was need site with simple CMS manager and with photo album. Also I wanted to practice in using Mootools library with Google API. So I decide use Blogger as site holder and CMS manager, Google Pages as javascript and images holder and Picasa as album manager. A structure of the site you can see on following diagram.

   

I have google account. If you have google account you can use it for registration on blogger.com, pages.google.com and picasa.com.  So in blogger I created blog per page on my site. A main page blog I used to entring point to my site. Also I customized XML template of the blog. I changed the layout of page according to my design, and deleted all old content of XML. In additional I added to header, links to javascript and CSS files.
So the base of my site was created.
I started javascript coding. The structure of content you can see on following diagram.




When user pressed on button in menu bar, I started loading content from blogger according to the button. 
You can see the script that do it at: http://panshinspace.com/lib/blog.js

The following script is loading all post of blog in Json format.


 

 

var script = document.createElement('script');

var src = 'http://www.blogger.com/feeds/'+

            this._blogId+

            '/posts/default?alt=json-in-script&callback='+

            this.options.objName+

            '.onGetDataComplete';

if(this.options.orderBy)

     src += '&orderby='+this.options.orderBy;

        

script.setAttribute('src', src);

script.setAttribute('id', 'blogJsonScript_' + this._blogId);

script.setAttribute('type', 'text/javascript');

 

document.documentElement.firstChild.appendChild(script);

 



After loading the script call to function that run by Json objects and fill content holder with content.

A script that loading albums from Picasa look different but concept is same: http://panshinspace.com/lib/album.js



Home Wedding Albums Travel Programming

©Yuri&Viki Panshin 2007