Sai Stuff to Developers

September 3, 2014

Problem with ASP.NET using MySQL Connecting through ODBC Driver in some Hosting Servers

Filed under: DotNet — tosaik @ 9:48 am
Tags: , , , , , , ,

Recently i hosted one of my asp.net 4.0 application which is using MySQL as backend and i decided to use MySQL .NET connector to access the MySQL server. I hosted one of the local server and its works fine but i got some consistency issues with my local server and decided to shift my application to GoDaddy which they ensure our application will be 24 X 7 in active.

I moved the application successfully but when i try to run the application through browser i cannot able to connect to database when i dig in to the issue through my logs i came to know that GoDaddy doesn’t support MySQL .NET connector DLL because GoDaddy will run only components and application which are Fully Trusted. When i read the blogs regarding this DLL i came to know Oracle has built this component as partial trusted (medium trust) which means i cannot use anymore with my application to host in GoDaddy. But here i have 2 options

  1. Need to place my MySql .Net connector component to the GAC of GoDaddy server.
  2. Need to remove using MySql .Net connector component in my application.

In the above options, option-1 GoDaddy doesn’t allow me to do so. Now i have only option-2, i removed code related to MySql .Net connector component and removed the reference to it and i try to connect mySQL database through ODBC (Object Database Connector). Which i successfully implemented in my application and working fine on my local computer and i updated the same over the hosting server (in my case GoDaddy), Interestingly still i am unable to connect to the Database, Now when i log my application to find the root cause of the issue, following are the error its throwing:

Request for the permission of type ‘System.Data.Odbc.OdbcPermission, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’ failed.

OOPS, i realized that GoDaddy also need my application to be fully trusted which i need to configure in my application via. web.config in System.web section as shown below:

 

<trust level="Full"/>

Once i changed this and made my application full trusted with this simple configuration change, My Application working like a charm.

The reason behind on writing this post is, i worked nearly 5 hrs to fix this issue and i cannot find any direct help from any blogs so i decided to keep this information in my blog to make others time save.

Thank You,

Happy Coding…..

 

October 29, 2013

Windows Store apps for Absolute Beginners with C#

Filed under: DotNet,Windows Apps — tosaik @ 8:12 am
Tags: ,

In this lesson Bob kicks off the series talking about the organization, required setup and goals of the lessons, and provides some motivation and guidance for getting started.   Resources C# Fundamentals: Development for Absolute Beginners.
source: channel9
<!–

October 1, 2013

Launched New Technology Site developersfusion.com

Hi Friends,

I have recently launched a new Technology WebSite www.developersfusion.com .

 

About Developers Fusion

Developers Fusion is a place where the professionals can share their experience and views contributing knowledge to the developer’s community. A successful professional, learns, explores, matures and finally contributes.

The developersfusion.com works with an idea, that has a big vision of bringing Technology to the cozy of your room wherever you are, and make learning comprehensive and exploring Technology real simple and easy.

We are dedicated in providing our Readers quality implementation, education, documentation and solutions. Our ultimate goal is to provide our readers with appropriate solution to their technical questions and needs. The developersfusion.com personifies the passion for Software Technology, delivers power in the technology and the skills associated with it, and enhances the productivity of professionals who shape the software field.

The developersfusion.com believes that it is vital to make learning Technology easy and effective and help its readers, technical breakthroughs in their future career along with other sessions that make them more informed about things that happen around them.

The Articles section lists articles published from different professionals enabling our readers to learn what’s new in the market and also the experience of the author. The FAQs section enables readers to prepare for answering the interview questions shot at them.

Our Vision

Bringing Technology to the cozy of every developer room wherever you are, and make learning comprehensive and exploring Technology real simple and easy.

Our Goal

Our ultimate goal is to provide our readers with appropriate solution to their technical questions and needs.

 

Hope all you make my new website a grand success by visiting posting and participating in forums etc…,

 

Regards,

Sai Kumar K

April 23, 2013

Finding count of Prime Numbers contain for a given Number

Filed under: DotNet,OOPS Languages — tosaik @ 11:44 am
Tags: , , , ,

Recently I need to add some of this kind of functionality in my on-going project and for that i wrote some simple method to returning the count of prime Numbers contain for given input number…. so i just want to have this snippet in front of you… Hope it will help as.. as it is simple but while implementing it kills our brain surly 🙂


static int getNumberOfPrimes(int N) {
	
    int count = 0;
    bool res = false;
    for(int i=2;i<=N;i++)
    {
        res = false;
        for(int j=2;j<=i;j++)
        {
            if(i%j == 0 && i!=j)
            {
                res = true;
            }
        }
        if(!res)
            count++;
    }
    
    return count;

}

Hope it will help for you 🙂

December 4, 2012

Unobtrusive Validation in Framework 4.5 Data Validations

Filed under: DotNet — tosaik @ 7:41 am
Tags: , , , , ,

Today I was working on ASP.NET web application on framework 4.5; I came across a strange error which I never experienced in my past working on earlier environments of dot net framework and that is error titled

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for ‘jquery’. Please add a ScriptResourceMapping named jquery(case-sensitive).

When I dig in to this issue and found the root cause of this issue and here my case study about this issue…

Unobtrusive Validation is a new concept in Framework 4.5, and this is by default enables when we create a new ASP.NET web application by adding one of the key in a Web.Config->appsettings section as below

 <add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms" />

What exactly this validation does for us

Forms with complex data including validators tend to generate too much JavaScript code in the page, which can represent about 60% of the code. With unobtrusive validation enabled, your HTML code will look cleaner and tidier.

For example we will compare the HTML code generated by both configurations.

Case-1:

Steps to create the sample application without unobtrusive validation enabled (default for all earlier versions)

1)      Open Visual studio 2012 IDE and create a new Web Application as shown below

UV1

 

 

 

 

 

 

 

 

2)      Now Press F5 to start the web application.

3)      Right-click on the browser page, and select View Source option to open the HTML code generated by the application.

4)      Scroll through the page source code and notice that ASP.NET has injected JavaScript code in the page to perform the validations and show the error list.

UV2

5)      Select the Script tab and expand the “{your current page}.aspx” combo to see all the referenced scripts. Notice that there are no references to the jQuery library. The validations are performed using the Microsoft Ajax Libraries together with JavaScript code injected within the page.

Case-2:

Steps to create the sample application with unobtrusive validation enabled (default for all new version(s))

1)      Now you will enable unobtrusive validation. Open Web.Config and locate ValidationSettings:UnobtrusiveValidationMode key in the AppSettings section. Set the key value to WebForms.

<appSettings>
    <add key="aspnet:uselegacysynchronizationcontext" value="false" />
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms"/>
</appSettings>

2) Open the Global.asax.cs file and add the following using statement

using System.Web.SessionState;
using WebFormsLab.Model;
using System.Web.ModelBinding;

3)      Within the Application_Start method of the Global.asax.cs file, add the following code

ScriptResourceDefinition myScriptResDef = new ScriptResourceDefinition();
myScriptResDef.Path = "~/Assets/Scripts/jquery-1.7.1.min.js";
myScriptResDef.DebugPath = "~/Assets/Scripts/jquery-1.7.1.js";
myScriptResDef.CdnPath = "http://code.jquery.com/jquery-1.7.1.min.js";
myScriptResDef.CdnDebugPath = "http://code.jquery.com/jquery-1.7.1.js";
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", null, myScriptResDef);

4)      Open Site.Master. Add the code below to include a ScriptManager on the page to include a script reference to the jQuery client library.

<form runat="server">
<asp:ScriptManager ID="uxScriptManagerMasterPage" runat="server" EnableCdn="False">
<Scripts>
    <asp:ScriptReference Name="jquery" />
</Scripts>
</asp:ScriptManager>


5)      Now Press F5 to start the web application.

6)      Right-click on the browser page, and select View Source option to open the HTML code generated by the application. Notice that by enabling the unobtrusive validation ASP.NET has replaced the injected JavaScript code with data- *attributes.

UV3

Don’t want this feature enabled?

Simply add the following setting in your AppSettings section in your web.config if it doesn’t exist. If already exist make value as “none” as shown below

 <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />

Conclusion:

With Unobtrusive validation we reduce the unnecessary JavaScript code generation for all validation controls by asp.net runtime. As if we enable this validation the asp.net runtime by default get and use the jquery environment to perform these validations through this we can have least overhead of unwanted JavaScript code in our HTML page and it also effect the improvement in the performance and take less time in rendering and loading your pages.

I Hope you got advantage of this article…

Please drop a comment if you like it…

Thanks Happy Coding  🙂

November 19, 2012

BadImageFormatException: Could not load file or assembly ‘x’ or one of its dependencies. An attempt was made to load a program with an incorrect format.

Filed under: DotNet — tosaik @ 12:01 pm
Tags: , , , , ,

Exception:

BadImageFormatException: Could not load file or assembly ‘x’ or one of its dependencies. An attempt was made to load a program with an incorrect format.

Solution:

Hi Recenty i had faced this exception and when i digg in to this issue…. and i forgot that when we are using any COM Interop DLL components in our .EXE application we need to target the respective .EXE application platform as x86

Please change the target platform to x86 in the properties section and build again before using it..

 

 

 

 

 

 

 

Hope this solution works for you too………

October 15, 2012

Converting a String to Title Case or Camel Case in C#

Filed under: DotNet — tosaik @ 6:28 am
Tags: , , ,

Now I am going to show how we can convert a string to a Title case or we also say it as Camel Case. For example I have a string as shown here


string name = "sai kUmar";

Now I need to convert the above string to Title case or we also say it as Camel Case, for this we have a special class called TextInfo which exist in the System.Globalization namespace. This special class has a special method called ToTitleCase() and which accepts only one string parameter and we need to pass our string need to convert through this parameter as shown below..


System.Globalization.TextInfo myTI = new System.Globalization.CultureInfo("en-US", false).TextInfo;
name = myTI. ToTitleCase(name);

Output: Sai Kumar

Note: Please provide your Current Culture while initializing TextInfo class object.

Hope this will helps you…

Happy Coding 🙂

August 23, 2012

Solution for Parsing an Excel file in C# and the cells seem to get cut off at 255 characters

Filed under: DotNet — tosaik @ 8:10 am
Tags: , , , , ,

Problem: An excel sheet containing say 10 rows and in couple of columns in couple of rows having data with more than 255 characters. When I try to upload this file in ASP.Net application using traditional OLEDB provider I cannot saw the whole data in particular cell means which is chopping out or we can say trimming to 255 characters when loaded in to my dataset object.

Solution: Having done sleepless nights I found some solutions to fix this issue… those are presented below

Solution-1:

If your application is used only on one computer then you can directly go to the following registry settings and change the TypeGuessRows  value.

HKLM\Software\Microsoft\Jet\4.0\Engines\Excel\TypeGuessRows

64 bit systems:

HKLM\SOFTWARE\wow6432node\microsoft\jet\4.0\engines\excel\TypeGuessRows

By setting this value to zero, the all lines of your spreadsheet are scanned for type guessing, rather than the default of 8. If any text fields longer than 255 chars are encountered, then those columns are deemed to be memo fields.

Note that you are still not 100% guaranteed to get the right data types, depending on your data.

Note also the HKLM scope of this key though – it will affect every OleDB Excel import by any process on that machine and this lead to degrade performance depending on the size of the data.

Solution-2:

A second way to work around this problem (without modifying the registry) is to make sure that rows with fields, which have data 255 characters or greater, are present in the first 8 rows (default value of TypeGuessRows is 8) of the source data file.

Solution-3:

This is the recommended solution by me as there is no need to change any registry or take care to have those lengthy data to be in first 8 rows. Instead we have a tool called NPOI which can be download from npoi.codeplex.com.

Using this dll we can upload the spreadsheet without worrying of chopping your data and also it has many features like creating the spreadsheet on fly including charts, reports etc.., for more information you can find on this site npoi.codeplex.com.

Anyway reading data using this NPOI is different from the traditional OLEDB provider. Please find the following method which with return a Data Table object by sending the File Path and the respective SheetName as input.

 
public static DataTable getExcelData(string FileName, string strSheetName)
    {
        DataTable dt = new DataTable();
        HSSFWorkbook hssfworkbook;
        using (FileStream file = new FileStream(FileName, FileMode.Open, FileAccess.Read))
        {
            hssfworkbook = new HSSFWorkbook(file);
        }

        ISheet sheet = hssfworkbook.GetSheet(strSheetName);
        System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
        
        while (rows.MoveNext())
        {
            IRow row = (HSSFRow)rows.Current;

            if (dt.Columns.Count == 0)
            {
                for (int j = 0; j < row.LastCellNum; j++)
                {
                    dt.Columns.Add(row.GetCell(j).ToString());
                }

                continue;
            }

            DataRow dr = dt.NewRow();
            for (int i = 0; i < row.LastCellNum; i++)
            {
                ICell cell = row.GetCell(i);

                if (cell == null)
                {
                    dr[i] = null;
                }
                else
                {
                    dr[i] = cell.ToString();
                }
            }
            dt.Rows.Add(dr);
        }

        return dt;
    }

 May be I presented the solutions straight forward without more explanation or discussion but presently my motto is to provide you the reasonable and permanent solution for those who suffering with similar problem.

Hope this research and the code helps you a lot.. if so please drop a comment below which may be more encroached for me..

 

Happy Coding  🙂

June 19, 2012

How Inheritance is importance in Object Oriented Programming?

Filed under: C++,DotNet,OOPS Languages — tosaik @ 5:41 pm
Tags: , , ,

One of the important features in the Object Oriented Programming is Reusability, as we said above that it is always good way to reuse the already existing functionality rather than trying to create the same one again and again. By reusing the properties not only saves the time and money but also increases the reliability.

An advantage of inheritance is that modules with sufficiently similar interfaces can share a lot of code, reducing the complexity of the program.

The Benefits of Inheritance

  • Subclasses provide specialized behaviors from the basis of common elements provided by the superclass. Through the use of inheritance, programmers can reuse the code in the superclass many times.
  • Programmers can implement superclasses called abstract classes that define “generic” behaviors. The abstract superclass defines and may partially implement the behavior but much of the class is undefined and unimplemented. Other programmers fill in the details with specialized subclasses.

Happy Coding 🙂

May 17, 2012

Basic Concepts of C#

Filed under: DotNet — tosaik @ 12:23 pm
Tags: ,


Introduction:

      As C++ language, C# is an Object Oriented programming language. Generally many people spells C# as C#.Net (C Sharp dot Net), But here Microsoft developed .Net environment mainly for distributed applications( Sharing Processing between client and server) and in C#.Net Net signs that C# is used to develop only Distributed Applications but using C# we can develop any kind of Software applications including windows applications.

C# is a new language especially developed from scratch to work with .NET environment. Using C# we can write a webpage, XML based applications like web services, Components for distributed applications as well as desktop applications.

Writing First C# Program:

     Writing a program in C# language is similar as we write in traditional C++ language, if you are aware of C++ language its easy you to writing and understanding the C# Code. Anyway I will explain every line in our basic First C# program where we will cover the things using that we can write and understand a simple to complex programs. Let’s look at our first C# program.

Program 1-1:

 

Using System;

Namespace sai.CS

{

Class FirstCSProgram

{

Static void main()

{

Console.WriteLine(“This Is Our First CSharp Program.”);

Console.ReadLine();

Return;

}

}

}

Compiling and Executing the Program:

The above Program can be write on any text editor like notepad, editplus, vi editor(in Linux) etc..,  or we can use Visual Studio’s .NET IDE(Integrated Development Environment) designed by Microsoft especially to write, compile and Execute the .NET Compatible Languages, C# is one of the  .NET Compatible Languages the other compatible languages of .NET are VB.NET, J# etc..,

There are two ways of compiling the above C# Program.

1)   If you write this Program in Visual Studio’s .NET IDE, then there is no additional work do perform for Compiling and Executing the application. Just Use functional Key F5 or go to <Debug> Menu and select <Start Debugging >. The IDE internally complies and executes the application without any user interaction.

2)    In this method we manually compile and execute the above application using command Prompt. Now open you command prompt (Start->Run->cmd or command).

You can compile the program by simply using the C# compiler Tool (csc.exe) as shown below

Csc  FirstCSProgram.cs

 

As you press <Enter> Key this csc.exe tool will compile our application named FirstCSProgram.cs and creates an exe file with same file name such as FirstCSProgram.exe.

Now using type FirstCSProgram.exe in your command prompt to execute our sample first C# program.

Note: cs is the file extension for C# applications.

Important point: Before using the tools such as csc.exe in your command prompt you have to set some environmental variables, to set these environmental variables you have two choices first, you can run a batch file named vcvars32.bat which is located at <Microsoft visual studios folder>/common7/Tools Folder (here <Microsoft visual studios folder> location is where your visual studios installed). Second, you will find a <visual studios 2005 or 2008> command prompt in start Menu ->programs -> Microsoft visual studios 2005 or 2008 -> visual studios Tools-> visual studio 2005 or 2008 command prompt which automatically set up these environmental variable for you. So you can directly use the .NET tools here.

A Close Look at the Code:

Line 1:  The first line of our sample program is

Using System;

Here we are importing the namespaces using <using> keyword in the above statement system is the namespace and we are importing it in our program. I will explain what is this namespace and how to use it and its importance in our next session for now just remember that namespace is a group of similar type of items and every class should belong to a specific namespace.

Line 2: Our next line in our program defining a namespace to our class as shown below,

Namespace sai.CS

Here we can define a namespace to our class by simply writing a user defined namespace name preceding with <namespace> keyword.

Line 3: Opening flower braces ({) this indicates to the compiler that the block is opened or started, it is similar as we use in C++ programming Language. When the compiler occurs this opening braces it will crease a new space on the stack memory where it will declares the variables which is scope to that block only (in the next chapter I will explain about variables, declaring a variables and their scopes) and allocating some memory from that newly created space for that block. Like that the compiler maintains n number of variables on the memory.

Line 4: In line 4 of our program we are declaring the class and its name as shown below,

Class FirstCSProgram

In C# programming what ever the business logic you want to write should be in class block I will explain what is class and its uses in our coming chapters so don’t worry for now just remember that what ever you want to write should write under class block and every program should contain at least one class. A class contains an optionally variables and optionally methods or functions   here we can define a class by simply writing a user defined class name preceding with <class> keyword.

Line 5: Opening flower braces ({) as I explained above in line 3, but this braces opening indicates class block has opened to the compiler.

Line 6: As I said in the above line that a class contains an optionally variables and optionally methods or functions, here  now in line 6 we defined a function or method as shown below,

Static void main()

One important point should note by you that a program can contain multiple classes under one namespace but in that classes at least one class should contain this main() method because the compiler starts its job from this main() function, if you not mention this function in your program then the compiler cannot compile you program because it doesn’t know from where should it start compiling?, And raises an error. So if you can define a main() method as we defined in our program.

Note: A deep discussion on this main() method and their uses will be in coming chapters

Line 7: Opening flower braces ({) as I explained above in line 3 & 5, but this braces opening indicates main() method block has opened to the compiler.

Line 8:  This is the first statement in our main() method and note that every statement should end with semi colon(;). Here in the following statement console is the class in System namespace as  explained above and writeLine() is a static method I will explain you later what difference between static method and normal method for now just remember that static methods will call directly by its class name as in this case, In writeline() method we are sending a some text “This Is Our First CSharp Program.”  When the compiler read this line it just prints the text “This Is Our First CSharp Program.” On the command prompt at runtime.

Console.WriteLine(“This Is Our First CSharp Program.”);

Note: A console class is developed to read and print or write a text on the console i.e., on command prompt, this class contains a functions by using these methods we can read and print a

Text on the console.

In console class we have two methods to print a text on the command prompt there are WriteLine() and Write() method. Both prints the text on the screen but writeLine() method prints the text followed by a new line character (\n) with this every WriteLine() method writes text on separate new line. For example,

Console.WriteLine(“This Is First Line.”);
Console.WriteLine(“This Is Second Line.”);

The output will be


In the same example replace the WriteLine() Method with Write() method  as shown below

Console.Write (“This Is First Line.”);
Console.Write (“This Is Second Line.”);

The output will be


Line 9:  As we know by above discussion about the console class we said that we can read and print the text on the console, above we came to know how we can print a text on the console screen but how we will read a text written by user at runtime ?. The answer is as I said that console class has a functionality using that we can read and print a text, as we seen to print a text on the screen we used writeLine() and Write() method in console class to read we have another method ReadLine() the name itself resembles the functionality of this method i.e.., it reads the text which is written by user at runtime.

Console.ReadLine();

Let’s take one example program to know how ReadLine() method works and their important. Here I this example we accept two numbers from the user ar runtime and we print the sum of that two numbers. Here the Program.

using System;
namespace FirstCSprogram
{

class Program
{
static voidMain()
{
int a, b;

Console.Write(“Enter First Number : “);
a=int.Parse(Console.ReadLine());
Console.Write(“Enter First Number : “);
b = int.Parse(Console.ReadLine());
Console.WriteLine(“The Sum Of {0} and {1} Is : {2}”,a,b,(a +  b).ToString());
Console.ReadLine();
}
}
}

When you compile and run this program on console it will ask you to enter first number after entering the fist number and press enter again it prompts for second number after giving the send number it will calculates the sum of these two numbers and displays the result on the console. Here how the output screen will look like.

Note: As we have ReadLine() to read a line of text similarly we have another method Read() which reads the next character on the input stream.

Line 10: The next statement is

Return;

This statement indicates to the compiler that the end of the scope of its belonging Block. It return’s the control to its calling method which is waiting for this control on the stack memory.

Line 11, 12, and 13: These three lines indicating end of their block. As I explained that opening of the block is represented by Opening flower braces ({) similarly the closing of the block is represented by closing flower braces (}).

Happy Coding 🙂

Next Page »

Create a free website or blog at WordPress.com.