A Place for C Sharpers/.Netters

I Will do coding till last moment of life-Kiran Patil

Archive for the ‘.NET’ Category

How to Break Recursive function?

Posted by kiranpatils on June 26, 2009

Challenge:

I have one Recursive function which  should check for some condition if it matches then return true. But after match what it does it calls itself from last call stack. Means

Call 1

Recursive Call1 — -Here condition matches and i say retrun true; //expected result is it should stop executing the function. But it calls last Call 1 from Call stack — This is what i understood from the Web resources…some one can correct me if i am wrong :)

Solution:

Problem is fine but what’s the solution????..Here is the way i did it[Just for demonstration purpose]:


/// <summary>
 /// Counter Variable
 /// </summary>
 static int counter = 1;

 /// <summary>
 /// IsValid or not flag
 /// -- Keep it static else it won't work
 /// </summary>
 static bool isValid = false;

 private static void MyRecusiveFunction(int p)
 {
 //RESET STATIC VARIABLE TO FALSE
 isValid = false;

 //if condition matches
 if (counter == 2)
 {                
 //return true;
 //COMMENTED as it was not effective for returning
 //Earlier method return type was BOOL now it has
 //been replace with void as we can access static
 //variable from anywhere
 isValid = true;                
 }

 //if condition not achieved
 if (counter < p)
 {
 counter++;
 MyRecusiveFunction(p++);
 }

 }

Basic idea is using static variable and setting it when match found :)

Links :

http://www.c-sharpcorner.com/Forums/ShowMessages.aspx?ThreadID=37288


Posted in .NET | Leave a Comment »

Can I have a Switch Statement with more than one Case Criteria?

Posted by kiranpatils on June 23, 2009

Challenge:

How can i put more than one criteria for switch case??…I would like to achieve the below things:

if((condition1 == true) || (condition2 == true))
 {

 //I am inside..

}

How to do this with switch? Here is the way…

Solution:

//For C# Champs
switch (Nationality)
{
case "Indian":
case "Ind":
//Hey i am Indian
break;
}
‘For VB Champs
Select Case temp
 Case "Indian", "Ind"
 'Hey i am Indian
 Exit Select
End Select

Posted in .NET | Leave a Comment »

.NET Framework Common Namespaces and Types Poster

Posted by kiranpatils on May 30, 2009

Background:

This post is dedicated to guys who do believe in OOPS or eager to learn OOPS Concepts[Like me :) ].  Our .NET F/w is built heavily on OOPS concepts. So, if you see take any Class like System.Web.UI.WebControls.TextBox if you see it’s CD and dig more in it you will learn a lot:

image 

This is just one example if you take any Control/Class of .NET F/W you will understand more how it has been designed and why?

So it is always good to have all namespace and types poster with you always too look at it while you are having cup of coffee :)

 Framework Version

Download Link

3.5 http://www.microsoft.com/downloadS/details.aspx?familyid=7B645F3A-6D22-4548-A0D8-C2A27E1917F8&displaylang=en
2.0 http://blogs.msdn.com/photos/brada/images/524537/original.aspx

 

So, Grab this and take a print out of it and have fun :)

Programming With Fun!!

Posted in .NET, Uncategorized | Tagged: , | Leave a Comment »

Object does not match target type+Reflection

Posted by kiranpatils on September 18, 2008

Problem:

When invoking a method using MethodInfor.InvokeMemeber() Method using Reflection.

It gives “Object does not match target type“

Solution:

For solving this error you can do two things:

  1. Declare your method which you are going to invoke as Static. [Which I don’t want to use].
  2. create instance of your type using Activator.CreateInstance(TYPE) and pass it as a first argument to InvokeMember() Method.

So final code looks like this

Assembly assembly = Assembly.LoadFile(FullAssemblyPath)

Type foundType = assembly.GetType(“TYPETOGET”)

MethodInfo foundMethod = foundType.GetMethod(“METHODTOFIND”)

Object [] params = new object [] {‘A’, 1,’B’};

Object response = foundMethod.Invoke(Activator.CreateInstance(foundType ), params);

That’s it

Posted in .NET, Reflection | Tagged: | 3 Comments »

tinyint+invalid cast exception with DataReader

Posted by kiranpatils on April 2, 2008

today i had faced a wired error in my DAL it was throwing an error invalid cast my code is like this:

int empid = reader.GetInt32(“EMPID”); //throws invalid cast..

i checked it with my database schema EMPID is tinyint. which is main cause of an error..

Solution:

I had done R&D and come in to know that:

SQL SERVER Stored tinyint as 8bit[1byte] .so we can’t fetch it using getint32…so to fetch it i had changed my code to:

 int empid = Convert.ToInt32(reader.GetBytes(“EMPID”)); //worked 

Posted in .NET, SQL SERVER 2005 | Leave a Comment »

Use Predicate for complex Conditional Block[if..else]

Posted by kiranpatils on March 29, 2008

yesterday i had completed coding of my block which has too may if..else blocks….which goes too approx. 20-30 lines… it does simple logic as under:

1. Gets Value from Querystring

2.and based on value redirect my page to appropriate page..

for doing the above thing i had written following code[looks like garbage]..

———————————————————————————————————

private void CacheAndTransfertoNext(){

string EntryPoint = Request.QueryString["EntryPoint"];

if (!String.IsNullOrEmpty(EntryPoint)){

if (_emppresnter.SaveEmployee()){

//Redirect on Next Page Based on EntryPoint Value

if (EntryPoint == “1″){

Response.Redirect(“Page1.asp”);}

else if (EntryPoint == “2″){

Response.Redirect(“page2.asp”);}

else if (EntryPoint == “3″){

Response.Redirect(“page3.asp”);}

else if (EntryPoint == “4″){

Response.Redirect(“page4.asp”);}

else if (EntryPoint == “5″){

Response.Redirect(“page5.asp”);}

else if (EntryPoint == “6″){

Response.Redirect(“page6.asp”);}

else if (EntryPoint == “7″){

Response.Redirect(“page7.asp”);}

}

else

{

Response.Redirect(“Default.aspx”);}

———————————————————————————————————

 i thought that can’t i make it smaller..i got it using predicate..i had accompilished the task in four lines…:)

Here it is:

1. I need to create some classes[which are self explanatory].

URLList.cs

using System;

using System.Collections.Generic;

using System.Text;

using System.Configuration;

public class URLList{

private List<MyUrls> _bookerurl = new List<MyUrls>();public List<MyUrls> BookerUrlList{

get { return _bookerurl; }

set { _bookerurl = value; }}

public URLList(){

_bookerurl.Add(new BookerURL(“1″,“page1.asp”));_bookerurl.Add(new BookerURL(“2″,“page2.asp”));__bookerurl.Add(

new BookerURL(“3″,“page3.asp”));__bookerurl.Add(new BookerURL(“4″,“page4.asp”));__bookerurl.Add(

new BookerURL(“5″,“page5.asp”));__bookerurl.Add(new BookerURL(“6″,“page6.asp”));}

}

using System;

using System.Collections.Generic;

using System.Text;

public class MyUrls

{

public MyUrls(){

}

public MyUrls(string key, string value){

_key = key;

_value = value;

}

private string _key;public string Key{

get { return _key; }

set { _key = value; }}

private string _value;public string Value{

get { return _value; }

set { _value = value; }}

}

——————- Now Lets see my Function now..

private void CacheAndTransfertoNext()

{

string EntryPoint = Request.QueryString["EntryPoint"];if (!String.IsNullOrEmpty(EntryPoint)){

if (_emppresnter.SaveEmployee()){

 URLList urlist = new URLList();
 MyUrls _nexturl = urlist.BookerUrlList.Find(delegate(MyUrls url) { return url.Key == EntryPoint; });                                        
string nextpageurl = (_nexturl != null) ? _nexturl.Value :  ”Default.aspx”;

Response.Redirect(nextpageurl);

}

}

Posted in .NET | Tagged: | Leave a Comment »

Generating guid(Globally Unique Identifier) with .NET

Posted by kiranpatils on March 19, 2008

I was playing with guid..initially i was getting same guid it was generating same Guid(000-000….)for all time…i was wondering about its strange behaviour..the code what i had written for it is as under:

//Not working

 public static Guid GetGuid()
{
return new Guid()

  }

at last i  found it’s solution:

 public static Guid GetGuid()
{
return Guid.NewGuid();
}

it will give new Guid everytime you call this function..Looks good na??Magic of NewGuid()!!!!

312a12b4-9853-45d2-8ccf-6d59ec940b41

NOTE: you can copy[if you can do try cut ] paste to you class call it.It will give you proper value means GUID

Happy guid!!!

Posted in .NET | Tagged: , | 1 Comment »

Invalid length for a Base-64 char array+RijndaelManaged/Encryption

Posted by kiranpatils on March 13, 2008

I am playing with Encryption/Decryption. and its good experience. Actually i have to encrypt a Guid and have to pass it in Querystring and have to get that Querystring and again have to decrypt data based on Querystring so i will get my origianal GUI.

First My Code looks like this:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace RfcDemoPwdGenerator
{
class Helper
{
private static string password = “ABC”;
private static int iterations = 1024;
private static byte[] salt = Encoding.ASCII.GetBytes(“This is My Salt value”);
/// <summary>
/// this function will take a plaintext as an arg and
/// returns ciphertext as an O/P
/// </summary>
/// <param name=”plaintext”></param>
/// <returns></returns>
public static string Encrypt(string plaintext)
{
Rfc2898DeriveBytes KeyBytes = new Rfc2898DeriveBytes(password, salt, iterations);
//The deafault iteration count is 1000
RijndaelManaged alg = new RijndaelManaged();
alg.Key = KeyBytes.GetBytes(32);
alg.IV = KeyBytes.GetBytes(16);
MemoryStream encryptStream = new MemoryStream();
//Stream to write
CryptoStream encrypt = new CryptoStream(encryptStream, alg.CreateEncryptor(), CryptoStreamMode.Write);
//convert plain text to byte array
byte[] data = Encoding.UTF8.GetBytes(plaintext);
encrypt.Write(data, 0, data.Length); //data to encrypt,start,stop
encrypt.FlushFinalBlock();//Clear buffer
encrypt.Close();
return Convert.ToBase64String(encryptStream.ToArray());//return encrypted data
}

/// <summary>
/// this function will take a ciphertext as an arg and
/// returns plaintext as an O/P
/// </summary>
/// <param name=”plaintext”></param>
/// <returns></returns>
public static string Decrypt(string ciphertext)
{
Rfc2898DeriveBytes KeyBytes = new Rfc2898DeriveBytes(password, salt, iterations);
//The deafault iteration count is 1000
RijndaelManaged alg = new RijndaelManaged();
alg.Key = KeyBytes.GetBytes(32);
alg.IV = KeyBytes.GetBytes(16);
MemoryStream decryptStream = new MemoryStream();
//Stream to read
CryptoStream decrypt = new CryptoStream(decryptStream, alg.CreateDecryptor(), CryptoStreamMode.Write);
//convert plain text to byte array
byte[] data = Convert.FromBase64String(ciphertext); //This guy was throwing an error Invalid length for a Base-64 char array
decrypt.Write(data, 0, data.Length); //data to encrypt,start,stop
decrypt.Flush();
decrypt.Close();
return Encoding.UTF8.GetString(decryptStream.ToArray());//return PlainText
}
}
}

Solution

Why this Error?

Sometime it works fine and sometime it fails. It made me frustrated..googled it too..then also :( .

so started noting down Plaintext,URL String,Cipher text and at last got the solution and root of problem. getting excited to know it..here it is…

*********THE SOLUTION**********
Plain Text[My guid] = 72e3f882-9e0e-434f-bf51-28cffc1903c1
Cipher TEXT[generatd by my Encrypt block] = 5NGETiEwyYy3F+P+QnzkRUeB5l7xUTRJuhhGZmFwi5WxCfeo3+kCvTs0z9s+CnZW
Querystring[encrypted guid] = 5NGETiEwyYy3F P QnzkRUeB5l7xUTRJuhhGZmFwi5WxCfeo3 kCvTs0z9s CnZW

Have you seen the change in Querystring???

My Cipher contains “+” and when i pass it in Querystring it ” ” it passes[space]…

That’s the solution dude….

so for solving it just have to change the following block of Decrypt string

byte[] data = Convert.FromBase64String(ciphertext); //OLD ONE

byte[] data = Convert.FromBase64String(ciphertext.Replace(” “,”+”)); //NEW ONE
Hope it wiill save your time which i had wasted/invested…

Happy Encrypting/Decrypting!!!

Resource: http://blogs.msdn.com/shawnfa/archive/2005/11/10/491431.aspx

Posted in .NET, ASP.NET | 18 Comments »

Why C# doesn’t supports multiple inheritance?

Posted by kiranpatils on March 10, 2008

Its good to know that  C# Supports Multiple Inheritance . But i  wrote  my  title that it  doesn’t. Yes  it doesn’t support by Implementation inheritance but supports using Interface  Implementation.  Sounds confused??  have a look at it…

Basic Inheritance


Two types of Inheritance:
1.    Implementation Inheritance: in which class inherits one class and implement/override its methods and properties for example Control object in which System.Windows.Forms.Textbox,System.Windows.Forms.Button both inherits their self from control class. But provides different functionality
2.    Interface inheritance: in which a class inherits from Interface. For example IDisposable. It just inherits definition not implementation. Any type which does interface inheritance it means that it will provide defined functionality called as “Contract”.

Multiple Inheritance:
A class derives from more than one class it is called Multiple inheritance
Multiple inheritance allows a class to take on functionality from multiple other classes, such as allowing a class named StudentMusician to inherit from a class named Person, a class named Musician, and a class named Worker. This can be abbreviated StudentMusician : Person, Musician, Worker.
Ambiguities arise in multiple inheritance, as in the example above, if for instance the class Musician inherited from Person and Worker and the class Worker inherited from Person. There would then be the following rules:
StudentMusician: Person, Musician, Worker
Musician : Person, Worker
Worker: Person
If a compiler is looking at the class StudentMusician it needs to know whether it should join identical features together, or whether they should be separate features. For instance, it would make sense to join the “Age” features of Person together for StudentMusician. A person’s age doesn’t change if you consider them a Person, a Worker, or a Musician. It would, however, make sense to separate the feature “Name” in Person and Musician if they use a different stage name than their given name. The options of joining and separating are both valid in their own context and only the programmer knows which option is correct for the class they are designing.
Debate
There is debate as to whether multiple inheritance can be implemented simply and without ambiguity. It is often criticized for increased complexity and ambiguity, as well as versioning and maintenance problems it can cause (often summarized as the diamond problem).[1] Detractors also point out multiple inheritance implementation problems such as not being able to explicitly inherit from multiple classes and the order of inheritance changing class semantics. There are languages that address all technical issues of multiple inheritance, but the main debate remains whether implementing and using multiple inheritance is easier than using single inheritance and software design patterns.

Multiple Inheritance arises Diamond Problem

programming languages with multiple inheritance and knowledge organization, the diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override it), and B and C have overridden that method differently, then via which class does it inherit: B, or C?

For example, a class Button inherits from both classes Rectangle (for appearance) and Mouse (for mouse events), and classes Rectangle and Mouse both inherit from the Object class. Now if the equals method is called for a Button object and there is no such method in the Button class but there is an over-ridden equals method in both Rectangle and Mouse, which method should be called?

It is called the “diamond problem” because of the shape of the class inheritance diagram in this situation. Class A is at the top, both B and C separately beneath it, and D joins the two together at the bottom to form a diamond shape.

C# Supports Multiple Inheritances by Interfaces only

NOTE: lots of help got from wikipedia

Happy Inheritance!!



Posted in .NET, OOP | Leave a Comment »

Checking Execution Time with C#.NET+ Use of it In WSSF+WCSF

Posted by kiranpatils on February 14, 2008

Today I am going to show you how to check an Execution time-Time taken by a function for executing its code block.

In today’s fast world all wants fast task [1Mbps, 1 Gbps…] and if your application’s response time is not fast than Boss you are lost with your application.

As per my Mind I ask “Why?” Why I need to check execution time because client wants final product for that I have to write code than why should I do this Execution time stuff.

For answering above question. Let us see some examples

Example1. Suppose you logged in your Banking site in which you have link called “View last transactions” and suppose that you are a shop keeper and have a current account than it’s obvious that you will have so many daily transactions. Now you clicked on link and from last 10 mins. Page says “Please wait…..” I am sure that you will close the browser window and will go physically at bank’s branch and ask for bank statement. [Gradually people won’t believe in software, applications means our Job is in danger.]

Example2. Now suppose you have U.S.A. Client for whom you are creating one software. And if response time is too slow than he will say “Indian peoples can’t create good software”. And will suggest to others also that don’t ask Indian people to develop your software. [Everything will be ost!!!!!!].

Now you are agree with me that response time is too important in our field.

So, let’s have a look on it how to do it with C#.NET with one example.

  1. I have created one Console Application for testing it. Its code is shown as below.

DateTime ExecutionStartTime; //Var will hold Execution Starting Time

DateTime ExecutionStopTime;//Var will hold Execution Stopped Time

TimeSpan ExecutionTime;//Var will count Total Execution Time-Our Main Hero

ExecutionStartTime = DateTime.Now; //Gets the system Current date time expressed as local time

//this is the main block for which we are checking execution Time

for (int i = 0; i < count; i++)

{       //Code of Block to do Execution

      Console.WriteLine(“Hi i am”+i.ToString());

      Console.Clear();

}//Execution Completed

ExecutionStopTime = DateTime.Now; //Gets the system Current date time expressed as local time

//Now Just calculate the duration taken by a Block

ExecutionTime = ExecutionStopTime – ExecutionStartTime; //Total Time

Console.WriteLine(“********Execution Time Summary*********”);

Console.WriteLine(“Loop Count = “+count.ToString());

Console.WriteLine(“TotalHours = “ + ExecutionTime.TotalHours.ToString());//Total Hours Console.WriteLine(“TotalMinutes = “ + ExecutionTime.TotalMinutes.ToString());//TotalMinutes            Console.WriteLine(“TotalSeconds = “ + ExecutionTime.TotalSeconds.ToString());//TotalSeconds            Console.WriteLine(“TotalMilliseconds = “ + ExecutionTime.TotalMilliseconds.ToString());//TotalMilliseconds            Console.WriteLine(“***************************************”);

OutPut when Input = 10000

image0011.jpg

Means my function has taken 2.03125 Second and 2031.25 Milliseconds.

So now just check the function do some “Code optimization” and check the Execution time. Decrease it as possible as you can.

Quick Check:

  1. Before execution starts take time using DateTime.Now
  2. After execution stops take time using DateTime.Now
  3. Check a difference using TimeSpan-which has so many useful properties.
  4. That’s it.

Real world use in WSSF+WCSF:

Microsoft has developed software factories and repository factories and they say that it has too quick response time. But than how you will check it that your service has been written good enough to respond quickly.

You can use the above steps for checking service response time also. Let me show with one example how you can do it.

Example:

  1. I guess that you have Service ready in WSSF Solution and eager to test it with Client Side-WCSF.
  2. Now come to WCSF and add Reference of your service let’s say “Employee Proxy”.
  3. Employee Proxy has one function “BookingProxy.BookingResponse GetEmployeeByID(BookingProxy .bookingrequest)”
  4. Now when you call your service using BookingProxy in Controller before calling “GetEmployeeByID” service take a time as a start time
  5. and when service returns [next line of GetEmployeeByID] take this time as a Stop time
  6. Do a TimeSpan and you will have a time taken by your service.
  7. So now you will have a code which looks like as under:

DateTime ExecutionStartTime = DateTime.Now;

BookingProxy.BookingResponse response = GetEmployeeByID (BookingProxy .bookingrequest);

DateTime ExecutionStopTime = DateTime.Now;

TimeSpan ExecutionTime = ExecutionStopTime – ExecutionStartTime;

Note it down and Enjoy!!!

Happy Executing optimum code block!!!!

-Kiran Patil

Reference Link:http://www.codersource.net/csharp_measure_execution_time.aspx

Posted in .NET, Web Service software Factory, Windows service Factory3.0 | 1 Comment »