Shalvin Interests

Sunday, December 27, 2015

C++ File Handling

Program to create a file and put value to it 

The header file for C++ file handling is fstram.h. We are making use of Output stream (ofstream) for outputting data from Program to file. Here the open method of ofstream class is used for opening the file. It is also possible to use the constructor of ofstream class.


#include <iostream.h>
#include <fstream.h>

int main()
{
    ofstream flout;
    flout.open("marks.dat", ios::out);
    char ans = 'y';
    int rollno;
    float marks;
    while(ans == 'y' || ans == 'Y')
    {
        cout<<"\n Enter Rollno. : ";
        cin>>rollno;
        cout<<"\n Enter Points :";
        cin>>points;
        flout<<rollno<<'\n'<<points<<'\n';
        cout<<"\n Want to enter more records?(y/n)..";
        cin>>ans;

    }
    flout.close();
    return 0;

}


The text file will be created in the bin folder.




Program to input details of 5 students and display them
This progam makes use of ofstream and ifstream classes.



#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>

int main()
{
    system("cls");
    ofstream fout("student", ios::out);
    char name[30], ch;
    float marks = 0.0;

    //Loop to get 5 records
    for(int i = 0; i<5;i++)
    {
        cout<<"Student"<<(i+1)<<":\tName:";
        cin.get(name, 30);
        cout<<"\t\tMarks:";
        cin>>marks;
        cin.get(ch);
        fout<<name<<'\n'<<marks<<'\n';

    }
    fout.close();
    ifstream fin("student", ios::in);
    fin.seekg(0);
    cout<<"\n";

    for(i=0;i<5;i++)
    {
        fin.get(name, 30);
        fin.get(ch);
        fin>>marks;
        fin.get(ch);
        cout<<"Student Name :"<<name;
        cout<<"\tMarks :"<<marks<<"\n";
    }
    fin.close();
    return 0;
}

Writing to and reading from multiple files in succession

#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>

int main()
{
    system("cls");
    //Create two files
    ofstream fileout;
    fileout.open("Stunames", ios::out);
    fileout<<"Arundhati \n"<<"Lakshmi \n"<<"Shalvin \\";
    fileout.close();
    fileout.open("stumarks", ios::out);
    fileout<<"100\n"<<"100\n"<<"95\n";
    fileout.close();

    //Read these files
    char line[80];
    ifstream filin;
    filin.open("stunames", ios::in);
    cout<<"The contents of studnames are given below\n";
    filin.getline(line, 80);
    cout<<line<<"\n";
    filin.getline(line, 80);
    cout<<line<<"\n";
    filin.getline(line, 80);
    cout<<line<<"\n";
    filin.close();

    filin.open("stumarks", ios::in);
    cout<<"\nThe contents of stumarks file are given below\n";
    filin.getline(line, 80);
    cout<<line<<"\n";
    filin.getline(line, 80);
    cout<<line<<"\n";
    filin.getline(line, 80);
    cout<<line<<"\n";
    filin.close();
    return 0;
}

Display contents of a file using get() function
get() function read a byte of data.


#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>

int main()
{
    system("cls");
    char ch;
    ifstream fin;
    fin.open("marks.dat",  ios::in);
    if(!fin)
    {
        cout<<"Cannot open file !!\n";
        return 1;
    }
    while(fin)
    {
        fin.get(ch);
        cout<<ch;
    }
    fin.close();
    return 0;

}

When end-of-file is reached, the stream associated  with the file becomes zero.

Output



Create a file using put() function
put() function will also write one byte at a time

The following program creates a ASCII chart of printable characters and displays them in 10 column format.


#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>

int main()
{
    system("cls");
    ofstream fout;
    fout.open("Aschars", ios::app);
    if(!fout)
    {
        cout<<"the file cannot be opened!!\n";
        return 1;
    }
    char ch;
    int line = 0;
    for(int i = 33;i<128;i++)
    {
        cout.put(((char)i));
    }
    fout.close();

    ifstream fin;
    fin.open("Aschars", ios::in);
    fin.seekg(0);
    for(i = 33;i<129;i++)
    {
        fin.get(ch);
        cout<<"  "<<i<<"=";
        cout.put((char)(i));
        if(!(i%10))
        {
            cout<<endl;line++;
        }
        if(line >> 22)
        {
            system("PAUSE");
            line = 0;
        }
    }
    return 0;
}

read() and write() functions for working reading and writing entire structure

#include <iostream.h>
#include <fstream.h>
#include <string.h>
#include <stdlib.h>
struct customer
{
    char name[51];
    float balance;

};

int main()
{
    system("cls");
    customer savac;
    strcpy(savac.name, "Shalvin P D");
    savac.balance = 10500.50;
    ofstream fout;
    fout.open("Saving", ios::out|ios::binary);
    if(!fout)
    {
        cout<<"File cannot be openened\n";
        return 1;
    }
    fout.write((char *) &savac, sizeof(customer));
    fout.close();

    ifstream fin;
    fin.open("Saving", ios::in|ios::binary);
    fin.read((char *) &savac, sizeof(customer));
    cout<<savac.name;
    cout<<" has the balance amount of Rs. "<<savac.balance<<"\n";
    fin.close();
    return 0;
}

Output



Tuesday, November 10, 2015

SharePoint Pragmatically Obtaining NewForm and EditFormUrl


protected void Page_Load(object sender, EventArgs e)
{
      SPSite site = new SPSite("http://abc-pc");

      SPWeb web = site.RootWeb;
      SPList list = web.Lists["Employee"];

      ListBox1.Items.Add(list.DefaultNewFormUrl.ToString());
      ListBox1.Items.Add(list.DefaultEditFormUrl.ToString());
}

SharePoint Filling a GridView with List Information based on the DropDownList Selection


protected void Page_Load(object sender, EventArgs e)
 {
     if (!Page.IsPostBack)
     {
            SPSite site = new SPSite("http://abc-pc");

            SPWeb web = site.RootWeb;

           
            DropDownList1.DataSource = web.Lists;
            DropDownList1.DataTextField = "Title";
            DropDownList1.DataBind();
            
    }
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
     SPSite site = new SPSite("http://abc-pc");

     SPWeb web = site.RootWeb;
     SPList list = web.Lists[DropDownList1.Text];
          
     var item = list.Items;
     GridView1.DataSource = item.GetDataTable();
     GridView1.DataBind();
}

Programatically adding items to SharePoint List



protected void btnAdd_Click(object sender, EventArgs e)
{
      SPSite site = new SPSite("http://abc-pc");

      SPWeb web = site.RootWeb;
      SPList list = web.Lists["Employee"];

      SPListItem li = list.Items.Add();
      li["Title"] = txtEmployeeName.Text;
      li["Location"] = txtLocation.Text;
      li.Update();
}

Wednesday, October 14, 2015

AngularJS for .Net Developers : Routes and AngularJS Seed

Just like Asp .Net MVC AngularJS too have Routes.
In AngularJS the difference is that it is client side Routing. Here you specify the Fragment Identified identified by #. The difference in using Fragment Identifier is it the Web Application is not making a round trip to the server which is an essential concept in Single Page Application.


A Module can have Config. Config in turn have Route.
In the previous example we hard coded Controller into View.

$routeProvider Service

The $routeProvider service is used to define a route.

AngularJS Seed

Instead of  manually creating the structure for AngularJS project we can make use of AngularJS Seed. AngularJS Seed will create the necessary routes, views, scripts, etc. for you.



Here I am adding AngularJS Seed to an empty Web Application Project.





App.js

App.js is present inside js folder.

angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives']).
  config(['$routeProvider', function($routeProvider) {
      $routeProvider
          .when('/view1', {
          template: '/partials/partial1.html',
          controller: MyCtrl1});
      $routeProvider
          .when('/view2', {
              template: '/partials/partial2.html',
              controller: MyCtrl2
          });
      $routeProvider
          .otherwise({ redirectTo: '/view1' });
  }]);


$routeProvider is having a when function which expects a Fragment Identifier, template, controller.

Template is a View or a piece of html functionality. Here when you access view1 fragment you will be accessing partial1.html template.



_LayoutAngular.cshtml

<!doctype html>
<html ng-app="myApp">
<head>
  <meta charset="utf-8">
  <title>My AngularJS App</title>
  <link rel="stylesheet" href="/css/app.css"/>
</head>
<body>
  <ul class="menu">
    <li><a href="#/view1">view1</a></li>
    <li><a href="#/view2">view2</a></li>
  </ul>

  @RenderBody()
  
  <div>Angular seed app: v<span app-version></span></div>

  <script src="/lib/angular/angular.js"></script>
  <script src="/js/app.js"></script>
  <script src="/js/services.js"></script>
  <script src="/js/controllers.js"></script>
  <script src="/js/filters.js"></script>
  <script src="/js/directives.js"></script>
</body>
</html>


Inside _LayouAngular.cshtml layout there are Urls.

ng-view

ng-view is the AngularJS equivalent of RenderBody in MVC or ContentPlaceHolder in Web
Forms.

Index.cshtml
@{
    Layout = "~/Views/Shared/_LayoutAngular.cshtml";
}
<h3>Shalvin P D - Index</h3>

<ng-view></ng-view>


Index.cshtml present inside Views/Angular is having the ng-view directive. Here the template will get injected.


Monday, August 24, 2015

Web Forms Contact Management with Entity Framework

We are going to revisit the Contact Management System in Web Forms with Entity Framework. The details of Contact Management is taken up in this blog. There are basically two tables, viz. ContactGroups and  Contacts.

I am using Asp .Net Web Forms Site so that there will be inbuilt Master Page.

I am using Entity Framework,  Generate from Database option, the details I have blogged here.

I  the Default.aspx I am using a GridView to display the Group details.

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
   
</asp:Content>

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
    <p>
        <a href="InsertGroup.aspx">Insert Group</a> <a href="EditDeleteGroups.aspx">Edit/Delete Groups</a>&nbsp;</p>
<p>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:BoundField DataField="GroupName" HeaderText="Group Name" />
        </Columns>
    </asp:GridView>
    <br />
</p>
    </asp:Content>

 ContactManagementEntities ctx = new ContactManagementEntities();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = ctx.ContactGroups.ToList();
            DataBind();

        }
    }



Inserting Records to Parent Table


<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" Runat="Server">
    <p>
        <asp:Label ID="lblMessage" runat="server"></asp:Label>
        <br />
        <asp:Label ID="Label1" runat="server" Text="Group Name"></asp:Label>
        <asp:TextBox ID="txtGroupName" runat="server"></asp:TextBox>
    </p>
    <p>
        <asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save" />
    </p>
</asp:Content>


public partial class InsertGroup : System.Web.UI.Page
{
    ContactManagementEntities ctx = new ContactManagementEntities();

   
    protected void btnSave_Click(object sender, EventArgs e)
    {
        var c = (from p in ctx.ContactGroups
                 where p.GroupName == txtGroupName.Text
                 select p).Count();
       
        if (c != 0)
        {
            lblMessage.Text = "Value already exist";
            txtGroupName.Text = "";
            txtGroupName.Focus();
        }
        else
        {

            ContactGroup cg = new ContactGroup { GroupName = txtGroupName.Text };
            ctx.ContactGroups.Add(cg);
            ctx.SaveChanges();
            Response.Redirect("default.aspx");
           
        }
    }
}

Here I am checking for uniqueness of entered value.


Edit and Delete Contact Groups


<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" Runat="Server">
    <p>
        <br />
        Select Group
        <asp:DropDownList ID="ddlGroup" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlGroup_SelectedIndexChanged">
        </asp:DropDownList>
    </p>
    <p>
        Group Name<asp:TextBox ID="txtGroupName" runat="server"></asp:TextBox>
    </p>
    <p>
        <asp:Button ID="btnEdit" runat="server" OnClick="btnEdit_Click" Text="Edit" />
&nbsp;<asp:Button OnClientClick ="return confirm('Do you wan't to Delete')" ID="btnDelete"  runat="server" OnClick="btnDelete_Click" Text="Delete" />
    </p>
    <p>
        &nbsp;</p>
</asp:Content>

public partial class EditDeleteGroups : System.Web.UI.Page
{
    ContactManagementEntities ctx = new ContactManagementEntities();
    protected void Page_Load(object sender, EventArgs e)
    {
        if(! IsPostBack )
        {
            ddlGroup.DataSource = ctx.ContactGroups.ToList();
            ddlGroup.DataTextField = "GroupName";
            ddlGroup.DataValueField = "GroupId";
            DataBind();
        }
    }
    protected void ddlGroup_SelectedIndexChanged(object sender, EventArgs e)
    {
         var Grp = GetGroup();
        txtGroupName.Text = Grp.GroupName;
    }

    private ContactGroup GetGroup()
    {
        int intGroupId = Int32.Parse(ddlGroup.SelectedValue.ToString());
        var Grp = (from p in ctx.ContactGroups
                   where p.GroupId == intGroupId
                   select p).FirstOrDefault();
        return Grp;
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        try
        {

            var Grp = GetGroup();

            ctx.ContactGroups.Remove(Grp);
            ctx.SaveChanges();
            Response.Redirect("Default.aspx");
        }
        catch (DbUpdateException due)
        {
            lblMessage.Text = String.Format("There is records in the Contacts table which points to this '{0}'. First delete the the records in Contacts table refering to {0} and then delete the record.", txtGroupName.Text);
        }
        catch (Exception ex)
        {
            lblMessage.Text = "An error has occured";
        }
    }
    protected void btnEdit_Click(object sender, EventArgs e)
    {
        var Grp = GetGroup();
        Grp.GroupName = txtGroupName.Text;
        ctx.SaveChanges();
        Response.Redirect("Default.aspx");
    }
}

Here I am writing a function called GetGroup which returns a single Contact Group based on the selection from Drop Down List.

On selecting an item from DropDownList I am filling the TextBox(es) with its corresponding data.

I  have also added exception handling to Delete so that Foreign key violation error is handled.


Wednesday, February 11, 2015

SharePoint SPWeb Class

using Microsoft.SharePoint;

 static void Main(string[] args)
        {
            SPSite s = new SPSite("http://toshiba-pc");

            SPWeb w = s.RootWeb;
            Console.WriteLine(w.Title );
            Console.WriteLine(w.CurrentUser);

            Console.WriteLine("");

         

            Console.WriteLine("All users");
             foreach (var item in w.AllUsers )
            {
                Console.WriteLine(item);
            }

             Console.WriteLine("Fields");
             foreach (var item in w.Fields)
             {
                 Console.WriteLine(item);
             }

        }