Monday, 30 September 2013

Insert Data using Jquery in ASP.NET Mvc2

Its simple single form page which includes

-  Fullname
-  Age
-  Save Button

On Save button click , you will get message using JQUERY in ASP.NET MVC2


Models :

 [Serializable]
public class UserModels
{
  public string Name { get; set; }      
  public int Age { get; set; }
  public string message { get; set; }
}
Controller :

public ActionResult Index()
{
    return View();
}


[HttpPost]
public ActionResult Save(UserModels inputModel)
{
    string message = string.Format("Created user '{0}' in the system.", inputModel.Name);
    return Json(new UserModels { message = message });
}


Views :


 
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
             $(function() {               
$("#personCreate").click(function() {
var person = getPerson();
if (person == null) {                      
alert("Specify a name please!");
return;
} // take the data and post it via json

$.post("User/Save", person, function(data) {
// get the result and do some magic with it
var message = data.Message;
$(
"#resultMessage").html(message);
});
});
});
function getPerson() {
var name =
$("#Name").val();

var age = $("#Age").val();
return (name == "") ? null : { Name: name, Age: age };
}
</script>
<h2>
Index</h2>
<div class="editor-label">
<label for="Name">
Name</label></div>
    <div class="editor-field">
<input class="text-box single-line" id="Name" name="Name" type="text" value="" />
</div>
<div class="editor-label">
<label for="Age">
Age</label></div>
<div class="editor-field">
<input class="text-box sinle-line" id="Age" name="Age" type="text" value="" />
</div>
<p>
<input type="submit" value="Save" id="personCreate" /></p>
<div>
<span id="resultMessage"></span>
</div>
</asp:Content>


I have just started MVC using JQUERY...If any correction pls suggest

 

Friday, 27 September 2013

Split string in group of n number (Ex : Group of 3)

Today , I needed one solution for spliting string in group of 3

String as "Ac1Imghsd345dsda"

My program is

static void Main(string[] args)
{IEnumerable<string> result = Split("Ac1Imghsd345dsda", 3);
}static IEnumerable<string> Split(string str, int groupSize)
{
return Enumerable.Range(0, str.Length / groupSize)
.Select(i => str.Substring(i * groupSize, groupSize));
}


I get an output strings in group of 3 as Enumerable form

Here no to need to convert in toCharArray then FOR Loop..

Simply do as shows....

 
Dear friends ,

Over the 1 year or so I have gone from primarily developing applications using .NET/C# and ASP.NET MVC for web development.

It’s been an amazing experience, but it can take some time to get used to a new language and platform.

I have found the more languages I learn, the easier it gets to pick up new ones. Many of the core concepts are the same, it’s just a matter of learning the peculiarities of each language/platform (unless you’re learning learning a whole new paradigm, like a functional language).

One thing I find useful when learning a new language is to try and relate certain features back to a language I know and understand. Of course, it’s important to learn the correct conventions for a new language, but that usually happens over time.
For the purpose of this post, I’m going to create a create category on Blog for C#/ASP.net beginners and other post ( Erros solutions category ) on same blog.

Adjust it :) :)

Thanks & regards,
Nihar Kulkarni & Family..

Thursday, 26 September 2013

Exception Handling in Java

An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following:
  • A user has entered invalid data.
  • A file that needs to be opened cannot be found.
  • A network connection has been lost in the middle of communications or the JVM has run out of memory.
To understand how exception handling works in Java, you need to understand the three categories of exceptions:
  • Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
  • Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation.
  • Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Exceptions Methods:

Following is the list of important medthods available in the Throwable class.
SNMethods with Description
1public String getMessage()
Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
2public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3public String toString()
Returns the name of the class concatenated with the result of getMessage()
4public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output stream.
5public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
 public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

The throws/throw Keywords:

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Try to understand the different in throws and throw keywords.
The following method declares that it throws a RemoteException:

import java.io.*;
public class className
{
   public void deposit(double amount) throws RemoteException
   {
      // Method implementation
      throw new RemoteException();
   }
   //Remainder of class definition
}
A method can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For example, the following method declares that it throws a RemoteException and an InsufficientFundsException:

import java.io.*;
public class className
{
   public void withdraw(double amount) throws RemoteException,
                              InsufficientFundsException
   {
       // Method implementation
   }
   //Remainder of class definition
}
 
 

Declaring you own Exception:

You can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes:
  • All exceptions must be a child of Throwable.
  • If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
  • If you want to write a runtime exception, you need to extend the RuntimeException class.
We can define our own Exception class as below:
class MyException extends Exception{
}
You just need to extend the Exception class to create your own Exception class. These are considered to be checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods.

Example:

// File Name InsufficientFundsException.java
import java.io.*;

public class InsufficientFundsException extends Exception
{
   private double amount;
   public InsufficientFundsException(double amount)
   {
      this.amount = amount;
   } 
   public double getAmount()
   {
      return amount;
   } 
 }

 

Friday, 20 September 2013

Hashtable in C#

 
Hi frnds, you couldn't believe about hashtable concept in c#.
 
I don't know ,how would I missed it. But its very helpful while searching for generic collections related techniques. I just viewed it , but never used it before.
 
So I am sharing some ways to use it at your place.
 
 
Members of hastable :  
 
Key :-  Unique value which can be number or character
 
Value :- Value you want to store on particular key
 
 
The example adds 15 distinct integer keys, with one string value each, to the Hashtable object.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace HashTableDemos
{
    class Program
    {
        static void Main(string[] args)
        {
            string _concat = "A";
            Hashtable _hash = new Hashtable(15);
            for (int _key = 0; _key < 15; _key++)
            {
                _concat = _concat + _key;
                _hash.Add(_key, _concat.ToString());
                Console.WriteLine("Key {0} ,Value {1} ", _key, _concat.ToString());
            }
            Console.ReadLine();
        }
    }
 
Output : Please check at u r side.....
 
 
Contains  method in Hastable:
 
Instance methods on the Hashtable ,which returns true if the key is found, regardless of the value.
 
Example: 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace HashTableDemos
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable hashtable = GetHashtable();
            // See if the Hashtable contains this key.
            Console.WriteLine(hashtable.ContainsKey("Perimeter"));
            // Test the Contains method. It works the same way.
            Console.WriteLine(hashtable.Contains("Area"));
            // Get value of Area with indexer.
            int value = (int)hashtable["Area"];
            // Write the value of Area.
            Console.WriteLine(value);
            Console.ReadLine();
        }
        static Hashtable GetHashtable()
        {           
            Hashtable hashtable = new Hashtable();
            hashtable.Add("Area", 1000);
            hashtable.Add("Perimeter", 55);
            hashtable.Add("Mortgage", 540);
            return hashtable;
        }
    }
}
 [Note :  But if we compare Hastable with Dictionary ... we found hashtable results slower than Dictionary. ]
 
 

Saturday, 14 September 2013

out and ref keywords in C#

As we already studied about  CALL BY REFERENCE  in C of our academic period.

In call by reference , we passed the address of that variable's value to method.

But due to point died in C# , we used REF  keywords in C#.

REF :

   Ref parameters are changed at the calling site. They are passed as references, not values. This means you can assign the parameter in the called method and have it also be assigned at the calling site.

  • There is a big difference between ref and out parameters at the language level. Before you can pass a ref parameter, you must assign it to a value.
  • This is for the purpose of definite assignment analysis.
  • You don't need to assign an out parameter before passing it to a method. The compiler allows this.
Sample program for understanding :

 
 public static void Main(string[] args)
{         int val = 1;
Method (ref  val);Connsole.WriteLine("By ref keyword :{0}" ,val); Console.ReadLine();
}

static void Method(ref int i)
{           
     i = i + 44;
}

Output :
By ref keyword : 45




Out :
  Outsignifies a reference parameter. Sometimes methods must return more than one value and not store class state. Out fills these requirements. With it we pass parameters whose changes are realized in their calling methods.

Sample program for understanding :

public static void Main(string[] args)
{bool period;
bool comma;
bool semicolon;
const string value = "has period, comma.";
TestString(value, out period);
Console.WriteLine(value);
Console.Write("period: ");
Console.WriteLine(period);
}

static void TestString(string value, out bool period)
{
period = comma = semicolon = false;for (int i = 0; i < value.Length; i++)
{switch (value[i])
{case '.':
{
period = true;
break;
} 
}

}

}


Enjoy...!! Please suggest correction if requried ..!!

 

Thursday, 12 September 2013

Defining values while creating sql table

Hi friends  ,

This post and technique very new to me !!
It reduce lot of repeated work while using SQL queries with other technologies like (C#,Java,Perl etc)

Basically post refers to CREATE TABLE command of SQL

Example : Guess that , you want to calculate percentage of total marks ,get to particular students and store it table.
For that process , we need to create columns as id,fname,lname,totalMarks,Percentage etc.
Then we go for code ,we calculate from insert or select query or others.

I am trying through SQL Server 2008 R2...

Create table of  sample student table :
 
create table SampleTable
(
      id int identity(1,1),
      fname nvarchar(50),
      lname nvarchar(50),
      totalMarks float,
    passFlag as case when  totalMarks> =50 then 'Pass' else 'Fail' end persisted
)

Insert record and select query :

 
I hope you enjoy it..!! Feel free to suggest corrections .
 

Saturday, 7 September 2013

return View() vs return RedirectToAction() vs return Redirect() vs return RedirectToRoute() ??

Here some points which elaborate difference between abouve signatures....

There are different ways for returning/rendering a view in MVC Razor. Many developers got confused when to use return View(), return RedirectToAction(), return Redirect() and return RedirectToRoute().
In this article, I would like to explain the difference among "return View()" and "return RedirectToAction()", "return Redirect()" and "return RedirectToRoute()".

return View()

This tells MVC to generate HTML to be displayed for the specified view and sends it to the browser. This acts like as Server.Transfer() in Asp.Net WebForm.

 public ActionResult Index()
  
return View();
}
[HttpPost]
public ActionResult Index(string Name)
{    
    ViewBag.Message = "Hi, welcome to Nihar's Blog !! ";    //Like Server.Transfer() in Asp.Net WebForm    
    return View("MyIndex");
}
 public ActionResult MyIndex()
   
   ViewBag.Msg = ViewBag.Message;     // Assigned value : "Hi, Welcome to Nihar's blog"   
    return View("MyIndex");
}
What happens if we call the action method directly like return MyIndex(). It is simply a method call which returns a rendered view that is specified in MyIndex() action method.

[HttpPost]
public ActionResult Index(string Name)
{
     ViewBag.Message= "Hi, Welcome to Nihar's blog"
    //Like Server.Transfer() in Asp.Net WebForm
      return MyIndex();
}


return RedirectToAction()

This tells MVC to redirect to specified action instead of rendering HTML. In this case, browser receives the redirect notification and make a new request for the specified action. This acts like as Response.Redirect() in Asp.Net WebForm.
Moreover, RedirectToAction construct a redirect url to a specific action/controller in your application and use the route table to generate the correct URL.

  public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(string Name)
{
    ViewBag.Message = "Hi, Welcome to Nihar's Blog";
    //Like Response.Redirect() in Asp.Net WebForm
   return RedirectToAction("MyIndex");
}

public ActionResult MyIndex()
{
     ViewBag.Msg = ViewBag.Message;
    // Assigned value : Null
    return View("MyIndex");
}



return Redirect()

This tells MVC to redirect to specified URL instead of rendering HTML. In this case, browser receives the redirect notification and make a new request for the specified URL. This also acts like as Response.Redirect() in Asp.Net WebForm. In this case, you have to specify the full URL to redirect.

  public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(string Name)
{
    ViewBag.Message = "Hi, Welcome to Nihar's Blog!!";
    //Like Response.Redirect() in Asp.Net WebForm
   return Redirect("Home/MyIndex");
}

public ActionResult MyIndex()
{
   ViewBag.Msg = ViewBag.Message;
   //Assigned value : Null
   return View("MyIndex");
}




return RedirectToRoute()

This tells MVC to look up the specifies route into the Route table that is is defined in global.asax and then redirect to that controller/action defined in that route. This also make a new request like RedirectToAction().

In global.asax 
     
     public static void RegisterRoutes(RouteCollection routes)
    {
     routes.MapRoute(
    "MyRoute", // Route name
    "Account/", // URL
    new { controller = "Account", action = "Login"} // Parameter defaults
    );
    routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "MyIndex", id = UrlParameter.Optional } //Parameter defaults
    );
    }

    In Controller :

public ActionResult Index()
 {
     return View();
 }

[HttpPost]
public ActionResult Index(string Name)
 {
        return RedirectToRoute("MyRoute");
 }
 
For this article I refer  Pro ASP.Net MVC 4 .
( For ref : http://www.amazon.com/Pro-ASP-NET-MVC-Adam-Freeman/dp/1430242361 )

Swap the values of two columns in SQL Server

 
Do you have fun with SQL Server?.
Suppose you want to swap the values of two columns of a table in SQL Server, how could you achieve this tricky task?. Actually, it is simple and so funny.
 
Suppose you have a Persons table in the database with the following data and you want to interchange the values of columns Name and Address then how do you do?

Query :

 Before swapping :
select * from [testdb1].[dbo].[persons]


P_Id       LastName            FirstName           Addr         City
1              Kulkarni                Nihar                     Pune        India
2              Gates                    Bill                          San Jose   US


After swapping :

update [testdb1].[dbo].[persons]
set [Addr]=[City],[City]=[Addr]
 
P_Id       LastName            FirstName           Addr      City
1              Kulkarni                Nihar                     India      Pune
2              Gates                    Bill                          US          San Jose
 
 
Time pass Solution. ..bt needful !!!!!
I know to tooooo simple solutions , but sometimes we forget ...
Enjoy..!!
 
 
 

Thursday, 5 September 2013

Column concatenation in SQL Server

Hi friends ,

Last week , I was facing one problem regarding column summary report. For that purpose , we tried joins,unions etc .

But we tried one query , which seems to be subquery  but some professional defined as pointer in sql server.

Post description as follows,

We need report of Students which include ,

Studentid,StudentName,Studentaddree,UnitTest1marks ,Absent hrs

Query :

select studId,studName,Studaddre,Sum(TEstMarks) ,ab.absentHrs
-- SUM(convert(float,a.[absent])) as absentHrs
From  StudPerformance.dbo.Card_Data a
inner Join StudPerformance.dbo.Rate_mast b On a.stud_cd = b.stud_no Anda.mach_cd = b.machine_cd
and a.proc_cd = b.process_cd
Join (Select a.stud_no,
    Sum(Convert(float,a.[absent])) / 60 As absentHrs
  From StudPerformance.dbo.Job_Card_Data a
  Where a.entry_date Between @p_from_date And
  @p_to_date And
    a.entry_date = a.entry_date And
a.class_group = 'FirstStd'
And a.class_group = a.class_group
  Group By a.studId,a.studAddre


Here Result will be as


Studentid,StudentName,Studentaddree,UnitTest1marks ,Absent hrs

Ab.absenthrs join as new column after execution completed.

I will share you more on this , bcos its nt concept . It will useful as logic for implementation.
Gud day!!





 

Tuesday, 3 September 2013

Summarizing of column values in SQL Server


Hi friends ,
here I am wondering about sql server by reading " ROLLUP " concept in SQL Server.

Consider the scenario which gives you  sum of columns within query , Is it possible  ?
Before reading it , I used different methods for summation of columns but Its tooo good to read it that , we will get sum in practicle way within query itself.

Highlighted row will be sum of RegId and Amount column.

Query as :

SELECT O_Id,Sum([OrderNo]) as RegId, SUM([p_id])  as TotalAmount
AS Amount FROM [testdb1].[dbo].[Orders]
GROUP BY O_Id
WITH Rollup

Order_Id  RegId TotalAmount  1              21          2
  2              2324      1
  3              32          2
  5              6            3
  NULL     2383      9            <---Here Summary of Column (Regid ,TotalAmount)

I am searching more about Rollup,Cube and other related concept . Till date you also search and inform me more.
Try it..!! Enjoy...






















 

CTE ( Common Table expression ) in SQL Server

Its very new concept for me, heard from Mr.Vinayak Sir.
Thanks to them.

CTE (Common Table Expression ) is nothing but return same result as SELECT query will do with the help of JOINS,UNION etc.

It allows you to define the subquery at once, name it using an alias and later call the same data using the alias just like what you do with a normal table.

Take a look at following difference between plain query with join and CTE query

Plain SQL query :

Its plain query.




CTE query :

Using CTE syntax/format , we define query as follows,

Syntax :

With [table_aliesname] ( userDefinedColumn1,userDefinedColumn2,userdefinedcolumnN )
As
(
[Plain SQL select query.]
)
-- If you want to join more table only need to give ',' comma for closing round bracket and continue as same as T2 table in Examle

 Regards,
 Nihar Kulkarni  :) :)