Skip to main content

Posts

Showing posts from 2012

Send Mail .NET

Allowing user to send mail (feedback, contact etc) is a very common feature in current web applications. In this series of post we will talk about some basic mail features and how to implement them in c#. Basics In order to send mail we need SMTP server configured as mails work over SMTP. You can configure SMTP server yourself or if you are using web hosting services you can get an account setup for you. In order to receive mails we need POP. For this tutorial series we will use gmail SMTP server.  .NET APIs .Net provides us with lots of classes present in System.Net.Mail to send an email. We will be using MailMessage, MailAddress and SmtpClient classes. We will create a MailHelper and will use it in Winforms, Asp.Net, Console etc. Mail Helper using System.Collections.Generic; using System.Net.Mail; namespace MailConsole { public class MailHelper { public static void SendMail(string subject,string message,List to) { var mailM

Knowing Singelton

Singelton pattern in one of the most commonly used and talked about design pattern . Many appreciates it usefulness and many advocate against it. In this post we are not going to discuss all that but will concentrate on its implementation in c#. Type: It is a creational design pattern . Intent: It ensures that only one instance of the class exists. Usage: It is generally used when only one instance of a class is required. Thus, it can be seen to be used in logging frameworks, configuration objects etc. The ownership of instance creation lies with the class itself. This is because we can not ensure that only one instance will ever exists for the class if the responsibility lies with someone else. The class will instantiate the object when it will be used for the first time. This also ensures lazy initialization. Point to consider: Singelton object is mostly made accessible globally and thus being abused by being used as global variable. We must keep in mind that not onl

C# Polymorphism - handle with care

Download Overriding is the base for most of the design patterns which exists. It provides us with an essential tool called  Polymorphism  . What is  Polymorphism  ? Polymorphism means one interface and many forms. It is a characteristics of being able to assign a different meaning or usage to something in different contexts specifically to allow an entity such as a variable, a function or an object to have more than one form.  There are two types of Polymorphism.  Compile time:  function or operator overloading  Runtime:  Inheritence & virtual functions Here, we are going to talk about the Runtime Polymorphism.  If you read the definition carefully you will see that there is going to be some type casting and compiler is going to made some assumptions. These assumptions may fail on execution. Let me explain this further. Type casting: There will be a parent interface (Interface, abstract class, class) and may be many child classes. These child classes will impl

c# reference types passed by value or reference

Download Time and again I have heard that in C#, method arguments are passed based upon there type. i.e. Value types are passed by value and reference types are passed by reference. This is so untrue. Reference types have nothing to do with pass by value. Let us talk some basic. Consider the assignment first. When you assign a value type to another its value is copied. This is because value type variable contains its data directly. When you assign a reference type variable to another only the reference gets copied. This is because a reference type variable does not contains its data directly. It only holds reference to data. Thus, when we pass a value type, its value gets copied and when we pass a reference type its reference gets copied. That is why if we change the value of a value type variable in the block (method), the change is not seen outside of it. On the other hand if we change the value of member of reference passed to the block from within the block the change persi

Callback in c#

Download Running tasks in background is the need of the hour when working on real world applications. There are few tasks which we can fire and forget but for few of them we will like to receive the feedback. This is when callbacks comes into the picture and provides a channel for these objects to communicate with each other. These tasks are very common in desktop and mobile applications. In this post we will talk about callback mechanism in c#. In future post we will build upon this and do lot more. Using interfaces for callbacks in c# using System; using System.Threading; namespace Callbacks { class Program { static void Main(string[] args) { var consumer = new Consumer(); consumer.DoWork(); Console.ReadLine(); } } interface IOnProcessCompleteListener { void OnProcessComplete(string message); } internal class Consumer: IOnProcessCompleteListener { private Work

Android - Disable Text Selection

In order to disable text selection in a WebView we can use following approaches: CSS * {   user-select: none; -moz-user-select: -moz-none; -khtml-user-select: none; -webkit-user-select: none; } This approach will not work on all the versions of Android as the support was not there till late. Handling LongClick public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);     WebView webView = (WebView) this.findViewById(R.id.webView1);     webView.loadData("<html><head><style>head><body>You scored           <b>192</b>     points.</body></html>", "text/html", null);                     webView.setOnLongClickListener(new View.OnLongClickListener() {         public boolean onLongClick(View v) {              return true;         }     }); }

Split String in C++ with delimiters

In order to split string in c++ we can use strtok(). A sequence of calls to this function split str into tokens, which are sequences of contiguous characters separated by any of the characters that are part of delimiters. On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.  Read More Here #include <iostream.h> #include <string.h> int main( int argc, char ** argv) {      // multiple delimiters can be provided      char const delimiters[] = "/:" ;          // initial string to split        std::string sCFIString = "/6/2702!/4/6/6/122/1:3" ;          // this pointer will point to the next word after every 'strtok' call      char *token = strtok(const_cast< cha

Convert std::string to char* and const char* - c++

Convert std::string to const char* std :: string name = "Anuj" ; const char * constName = name.c_str(); Convert std::string to char* std :: string name = "Anuj" ; const char * constName = name.c_str(); char * ptrToName = const_cast< char *> (name.c_str()); A simple progam  #include <iostream> #include <stdio.h> using namespace std; int main() {     std :: string name = "Anuj" ;      const char * constName = name.c_str();      char * ptrToName = const_cast< char *> (name.c_str());     printf( "%s" ,constName);     printf( "%s" ,ptrToName);     cout << name << endl;      return 0 ; }

Disable a hyperlink using javascript - jquery

I was working on an iOS application where we were displaying HTML content. We did not have control over these HTMLs and because of these we were facing lots of issues. One of the issue was handling of hyperlinks, we needed to handle the navigation ourselves. You can disable the hyperlink using the preventDefault() javascript function. Below is the sample using which you can disable the default behavior of a hyperlink. <html> <head> <script src="jquery-1.5.1.min.js" type="text/javascript"></script> <style></style> <script>   $(document).ready(function () {   $('a').click(function(e) {     e.preventDefault();             //do other stuff when a click happens     return false;  //In few browsers you will need to return false at the end     }); }); </script> </head> <body> <a href="www.google.com"> Google!!!</a> </body> </html> Note : In fe

Change selection background and color using css

It is always nice to have a cool UI for our website. Changing the background and foreground color of selection can do wonders sometimes. In this post I will show you how you can achieve that. We can do this easily using CSS3. It provides us with ::selection selector. Safari supports ::selection and firefox supports   ::-moz-selection.  Webkit browsers supports ::-webkit-selection. With time many browsers have started supporting ::selection itself. .content::selection  {     background: #E01624;     color:White; } .content::-moz-selection  {      background: #E01624;      color:White; } .content::-webkit-selection {      background: #E01624;      color:White; } .content {       overflow:hidden; } In HTML I have div with class as content. 

How to get html tag name of an html element using jQuery

Some times it is needed to get the tag name of an element. You can use below mentioned script to get that. <html> <head> <script src="jquery-1.5.1.min.js" type="text/javascript"></script> <script>   $(document).ready(function () {     alert( $('#someElement').attr('tagName') );   )}; </script> <body> <a  href="#">click to get tag name </a> <div id= 'someElement'> You want tag name of this element. </div> </body> </html

Difference between typeof() and GetType in c#

typeof() is used to get the type information from a type. Here type can be class, delegate, interface etc. e.g. Type t = typeof(Employee); GetType() is used to get the type information from the object. e.g. var obj = new Employee();        Type t = obj.GetType(); Thus, when you have an object you should use GetType function to extract Type information and when you have only a type with you then you should use typeof() operator to extract type information. 

Using Objective C files in C++ files (mm)

If you're using .mm files (C++) in your project, when you include the header files in .mm files header you may get below mentioned error (Even though you have all the right linker flags set): 1. linker failed with exit code 1 2. directory not found Solution: 1. Try adding the file to .mm file directly (not to .h file for .mm) 2. Try adding the file as extern extern "C" { #import "DetectDevice.h" }

Inversion of control - Part 1

When an object of a type depends on an object of another type we say that the types are coupled. This is because change in one can lead to a change in second. This will hamper the extensibility and modification in design. In a more complex system lot of classes interact with each other and this will lead to a very brittle design. Let's take an example:    class Program     {         static void Main(string[] args)         {             List<Employee> employees = new List<Employee>();             EmployeeController employeeController = new EmployeeController();             employees = employeeController.GetAllEmployees();         }     } Program depends on EmployeeController to fetch Employee(s).  Inversion of control Logically Inversion means rearrangement. As we have seen in the previous example that Program is controlling EmployeeController and this control is actually coupling them. Inversion of control is object-oriented practice via which we ca

We newbies and the application design and architecture

After being around for some time in this world of IT I have started to realize why these experienced guys are so furious with the newbies. I use to read a lot of newbie bashing on web and use to think WTF. Now, I must say "Old is Gold". There are three types of newbies I have come across. One who really do not want to design and just wants to get the job done in a procedural way. Second who know a thing or two about design and want to design there application the best possible way (constraint being there knowledge). Third who thinks they know everything about design and that is how things should be designed. The real problem arises when they are working on an application from scratch. The first type may come up with a class or two and finish the code in a monolithic manner. The third type will create a design either too good or to brittle. These two types will surely get the work done even though extensibility and maintainability may not be there and thus the cost of e

Learning C and or C++ on windows

If you want to start learning C/C++ and still want to use windows, you can either use Microsofts Managed C++ with a great IDE (Visual Studio) or GNU C/C++ compilers. Microsoft has invested a lot in C++ and Visual Studio. The powerful IDE really enhance the productivity. There is lot online documentation using which one can learn Microsoft's Managed C++ thick and fast. You can download Visual Studio Express for free and can start learning. Download Visual Studio 2010 express from here . Learning resources . If you want to learn GNU C / C++ you can start with downloading CodeBlocks. It is an IDE for GNU C / C++  and it comes bundled with the compiler which makes it really easy to install the compiler and avoid the complexities of getting the things in place pieces by pieces. You can download CodeBlocks from here .

The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid

It was 2 o'clock at night when I was creating a model (MVC) using Entity Framework. I thought of creating a UnitTest project to follow some TDD. When I tried to run my first TestMethod I got this vague exception. After investigating further with half closed eyes I found out, how dumb I was to not to include App.config in the test project.  Basic concept is pretty straight forward and logical. We generally add entity framework to a class library project in order to be able to reuse the library. The library project is not an executable in its own. Thus we need to add this project in some executable say a console App, windows App, ASP.NET or UnitTest. The runtime will then expect the executable to have a config associated with itself which will have the connection string, which entity framework library is looking for. Thus, the solution is pretty simple. Add the app.config to the project you are trying to run or add connection string to the config if the project you are tryin

Difference between ASP.NET web application and ASP.NET website

When we create web projects with ASP.NET we can either choose Web Application or Web Site. Both of these project types function and perform similarly, but they differ in many important ways which may impact are decision while creating the projects. Few of the differences are as follows: Reference - MCTS self-paced training kit (Exam - 70-515) 1.     You can create an MVC application. 2.     Visual Studio stores the list of files in a project file (.csproj or .vbproj), rather than relying on the folder structure. 3.     You cannot mix Visual Basic and C#. This is because files are stored .csproj or.vbproj and we have only one proj file. 4.     You cannot edit code without stopping a debugging session.  5.     You can establish dependencies between multiple web projects. 6.     You must compile the application before deployment, which prevents you from testing   a page if another page will not compile. In website projects all the pages are complied independent of each

Maintain scroll position on postback in ASP.NET

ASP.NET provides lot of cool and handy features and one of them helps us to maintain the scroll position on postback. This is how we implement it : <% @ Page Language ="C#" AutoEventWireup ="true" CodeBehind ="Home.aspx.cs" Inherits ="Ay.LearningApp.Home" MaintainScrollPositionOnPostback ="true" %> This will make sure that scroll position will be maintained at the page. In order to maintain the scroll position for all the pages we can change config file as follows: < configuration >     < system.web >         < compilation debug = " true " targetFramework = " 4.0 " />           < pages maintainScrollPositionOnPostBack = " true " />        </ system.web >    </ configuration > Happy coding!!! Cheers!!!

Working with BacgroundWorker class c#

Microsoft has provided BackgroundWorker class which make it really easy to create background threads easily. Sometimes we need to implement so functionalities in background threads so that UI will not freeze, that is when this class comes handy. Obviously we can create our own threads and manage there lifecycle ourselves but not everyone is efficient with threads and also sometimes the complexity hits back by consuming lot of time which we really do not have in case of rapid application development. When to use : Downloading a large file and showing progress bar. Uploading some information in background but letting the user to work. Creating a polling application etc. Usage: BackgroundWorker is also present in the toolbox and you can drag it from there or like any other control you can create an object at runtime and use it on the fly. It comes with various events and properties, few of them which are really important are: DoWorkEventHandler (event) Thi