Checking excel data file with C# class

January 22, 2014 Leave a comment

You need to check a large amount of data in excel file? Checking job is not simple and so trite. Refer the way creating a robot for checking not an bad idea. It also helps us more if it show an summary of provided data.

Excelfile

This is an example code for consulting class library. This ex checks wrong emails in some cases and show console summary.

Read more…

Categories: C#

How to increase debug time in ASP.NET or SharePoint

March 17, 2013 Leave a comment

Sometimes, time to debug is too short. It it an annoying issue. Here are some tips that we can solve this problem.

Follow these steps:

Step 1: Open IIS

image

Step 2: Open Application Pool

image

Step 3: Choose your application port that you’re working in.

image

Step 4: Click Advanced Settings

image

Step 5: Change some values in Process Model

– Ping Enabled : from “true” to “false”.
– Ping Maximum Response time (seconds) : from 30 to 999999

image

Final step: Click OK button on this popup window.

Enjoy and hope you success!!

Categories: ASP.NET, SharePoint

Apply LINQ to SharePoint with RunWithElevatedPrivileges()

March 17, 2013 Leave a comment

Introduction:

– LINQ to SharePoint is a way we query lists in SharePoint (beside CAML). Inside system, LINQ is compiled to CAML to query data. It is a little bit slow compared with CAML.

– RunWithElevatedPrivileges() is a method that we use when our permission is low than other user. In some cases, our code can not run if we don’t upgrade our permission.

Here is an small example about this topic:

using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Linq;

SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                string strUrl = "
http://<mywebapp>/sites/site1&quot;;

                using (SPSite oSiteCollection = new SPSite(strUrl))
                {
                    SPWebCollection sites = oSiteCollection.AllWebs;
                  
                    using (SPWeb web = oSiteCollection.OpenWeb())
                    {
                        //Console.WriteLine("Website: " + oWebsite.Url);
                        SPList list = web.Lists["Employees"];
                                        
                        //var query = from SPListItem p in list.Items where p["EmployeeID"].ToString() == "1" select p;

                        var query = from SPListItem p in list.Items
                                    where p["EmployeeID"].ToString() == "1"
                                    select new { ID = p["EmployeeID"].ToString() ,
                                                Name = p["Employee Name"].ToString()};

                        foreach (var item in query)
                        {                          
                            Console.WriteLine(item.ID);
                            Console.WriteLine(item.Name);                           
                        }
                    }
                }
                Console.Write("Press ENTER to continue");
                Console.ReadLine();
            });

Note: This is an example in console application. We should change platform to 64 bit app

image

Categories: LINQ, SharePoint

Read XML file in C#

March 12, 2013 Leave a comment

Sometimes, you need to do with xml file. Here are one example to get familiar with it:

We have xml file like this:

<All>
    <Drink>
         <Beer>heniken</Beer>
     </Drink>
     <Tree>
          <Apple>red</Apple>
          <Orange>orange</Orange>
          <Lemon>yellow</Lemon>
     </Tree>
</All>

We write some code to read it:

try
{
      using (StreamReader sr = new StreamReader("TestFile.xml"))
     {
         String line = sr.ReadToEnd();
         //Console.WriteLine(line);

         XmlDocument doc = new XmlDocument();
         doc.LoadXml(line);

        Console.WriteLine("Get one node: \r");
        XmlNode node = doc.SelectSingleNode("All/Drink/Beer");
        if (node != null)
        {
            string content = node.InnerText.Trim();
            Console.WriteLine(content);
        }

         Console.WriteLine("Get all node: \r");
          XmlNode node2 = doc.SelectSingleNode("All/Tree");
         if (node2 != null)
        {
             foreach (XmlNode item in node2.ChildNodes)
             {
                 Console.WriteLine(item.InnerText.Trim());
             }
            //string content = node2.InnerText.Trim();

        }
    }
}
catch (Exception e)
{
     Console.WriteLine("The file could not be read:");
     Console.WriteLine(e.Message);
}
Console.ReadLine();

Finally, you get the result as this screen:

Untitled

Hope you success! Thanks!

Categories: C#

Bitwise operators in C++

December 3, 2012 Leave a comment

Some operators:

image Sample:

#include <cstdlib>
#include <iostream>
#include <bitset>

using namespace std;

int main(int argc, char *argv[])
{
    unsigned short int a,b;
    cout<<"Enter 2 numbers: ";cin>>a>>b;
    cout<<"Amount of bytes: "<<sizeof(a)<<endl;
    cout<<"Binary of numbers:"<<endl;
    cout << bitset< 8 >( a ) << endl;
    cout << bitset< 8 >( b ) << endl;

    cout<<"Operator & :"<<endl;
    int temp = a & b;
    cout<<temp<<endl;
    cout << bitset< 8 >( temp ) << endl;

    cout<<"Operator | :"<<endl;
    temp = a | b;
    cout<<temp<<endl;
    cout << bitset< 8 >( temp ) << endl;

    cout<<"Operator ^ :"<<endl;
    temp = a ^ b;
    cout<<temp<<endl;
    cout << bitset< 8 >( temp ) << endl;

    cout<<"Operator << (multiply by 2 for 1 shift):"<<endl;
    temp = a << 2;
    cout<<temp<<endl;
    cout << bitset< 8 >( temp ) << endl;

    cout<<"Operator >> (divide by 2 for 1 shift):"<<endl;
    temp = a >> 2;
    cout<<temp<<endl;
    cout << bitset< 8 >( temp ) << endl;
    cout<<"Operator ~ :"<<endl;

    temp = ~a;
    cout<<temp<<endl;
    cout << bitset< 8 >( temp ) << endl;

    system("PAUSE");
    return EXIT_SUCCESS;
}

image

Categories: C++

Sorting and Searching Library in C++ (examples in array and vector)

November 22, 2012 Leave a comment

Sample template:

#include <cstdlib>
#include <iostream>
#include <vector>

using namespace std;
int values[] = { 40, 10, 100, 90, 20, 25 };
vector<int> v(values,values+6);
//For ascending sort in array
int compare_asc (const void * a, const void * b)
{
  return ( *(int*)a – *(int*)b );
}
//For descending sort in array
int compare_dsc (const void * a, const void * b)
{
  return ( *(int*)b – *(int*)a );
}
//Function for comparison in binary search
bool cmp_dsc (int i,int j) { return (i>j); }
bool cmp_asc (int i,int j) { return (i<j); }

int main(int argc, char *argv[])
{
    //Quick sort and binary search in array
    cout<<"Quick sort and binary search in array (ascending mode): ";
    qsort (values, 6, sizeof(int), compare_asc);
    for (int i = 0; i < 6; i++)
        printf ("%d ",values[i]);
    cout<<endl;       

    cout << "Looking for a 20… ";
    if( binary_search (values, values + 6, 20))
        cout << "found!\n"; else cout << "not found.\n";
    cout<<endl;

    //Descending mode   
    cout<<"Quick sort and binary search in array (descending mode): "; 
    qsort (values, 6, sizeof(int), compare_dsc);
    for (int i = 0; i < 6; i++)
        printf ("%d ",values[i]);
    cout<<endl;
    cout << "Looking for a 90… ";
    if( binary_search (values, values + 6, 90, cmp_dsc))
        cout << "found!\n"; else cout << "not found.\n";
    cout<<endl;

    //Sort and binary search in vector
    //Using default comparison
    cout<<"Sorting and binary search in vector (ascending mode): ";
    sort( v.begin(), v.end());
    for( int i = 0; i < 6; i++)
         printf ("%d ",v[i]);
    cout<<endl;
    cout << "Looking for a 40… ";
    if( binary_search (v.begin(), v.end(), 40))
        cout << "found!\n"; else cout << "not found.\n";
    cout<<endl;

    //Using myfunction as comparison
    cout<<"Sorting and binary search in vector (descending mode): ";
    sort( v.begin(), v.end(), cmp_dsc);
    for( int i = 0; i < 6; i++)
         printf ("%d ",v[i]);
    cout<<endl;
    cout << "Looking for a 20… ";
    if( binary_search (v.begin(), v.end(), 20, cmp_dsc))
        cout << "found!\n"; else cout << "not found.\n";
    cout<<endl;

    system("PAUSE");
    return EXIT_SUCCESS;
}

Result screen:

image

Categories: Algorithm, C++

Vector in C++ – Sample template

November 21, 2012 Leave a comment

Definition: Vector containers are implemented as dynamic arrays.

Source code:

#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <time.h>

using namespace std;

//Define a vector with type in < >
vector<int> my_vector (5);//Define a vector with amount of elements
vector<int> v;
//Can init value Ex: my_vector (10,0);vector<char> C(25, ‘A’);
//Two direction vector
vector< vector<int> > matrix(3, vector<int>(2,0));

void PrintVector(vector<int> val)
{
     //An other way to access the element
     for( vector<int>::size_type j = 0; j < val.size(); j++)
         cout<<val[j]<<" ";
     cout<<endl;
}
int main(int argc, char *argv[])
{      
    //Resize vector
    //my_vector.resize (10);
    my_vector.resize (10,-1);//can resize with init value Ex: my_vector.resize (15,1);

    //Insert value to the tail of vector
    v.push_back(3); v.push_back(1); v.push_back(2);
    v.push_back(7); v.push_back(6); v.push_back(5);
    v.push_back(4);
    cout<<"After push_back: ";PrintVector(v);

    //Insert value for a specific position
    my_vector.insert (my_vector.begin() + 0, 1);
    my_vector.insert (my_vector.begin() + 1, 2);
    my_vector.insert (my_vector.begin() + 2, 3);
    my_vector.insert (my_vector.begin() + 3, 4);
    my_vector.insert (my_vector.begin() + 3, 100);
    cout<<"After insert: ";PrintVector(my_vector);

    //Popback the last element
    my_vector.pop_back();
    cout<<"After pop_back: ";PrintVector(my_vector);

    //Remove element at position 3
    my_vector.erase (my_vector.begin() + 2);
    cout<<"After erase at index 2: ";PrintVector(my_vector);

    //Access the element using iterator
    vector<int>::iterator i;
    printf("Unsorted version: ");
    //Start with ‘begin()’, end with ‘end()’, advance with i++
    for (i = v.begin(); i!= v.end(); i++)
        printf("%d ",*i); // iterator’s pointer hold the value
    printf("\n");

            
    //Sort vector, default is ascending
    sort(v.begin(),v.end());
    printf("Sorted version: ");
    PrintVector(v);

 
    //Reverse vector
    reverse (v.begin(), v.end());
    cout<<"Reverse version: ";PrintVector(v);

  
    //Random values of vector
    srand(time(NULL));
    random_shuffle (v.begin(), v.end());
    cout<<"Random shuffle version: ";PrintVector(v);

 
    //Access value through index
    cout<<"The value at index 3 is: ";
    cout<<v[3]<<endl;
    cout<<"The value at index 5 is: ";
    cout<<v.at(5)<<endl;
    cout<<"Add value to the element indexed 3: ";
    v[3]+=100;
    cout<<v[3]<<endl;

 
    //Get Max, Min value of vector
    int highest = *max_element (v.begin(), v.end());
    cout<<"Max = "<<highest<<endl;
    int lowest = *min_element (v.begin(), v.end());
    cout<<"Min = "<<lowest<<endl;
    cout<<"Amount of all elements: "<<v.size()<<endl;//if use v.capacity() we need minus 1 unit

    //Count quantity of vector’s elements with specific value
    int num_zeros = count (v.begin(), v.end(),3);
    cout<<"Amount element having value 3: "<<num_zeros<<endl;
    v.clear();
    cout<<"After clear: ";
    if( v.empty() == true)
    {
        cout << "No values in vector.\n";
    }              

    cout<<"Using matrix with vector: \n";  
    for( int x = 0; x < 3; x++)
         for( int y = 0; y < 2; y++)
              matrix[x][y] = 1;
    for( int x = 0; x < 3; x++)
    {
         for( int y = 0; y < 2; y++)
              cout << matrix[x][y]<<" ";
         cout<<endl;
    }
    system("PAUSE");
    return EXIT_SUCCESS;
}

Result:

image

Categories: C++, Data Structure

Floyd’s Algorithm – All pairs shortest path

November 20, 2012 Leave a comment

Summary:

Computes shortest distance between all pairs of nodes, and saves P to enable finding shortest paths.

Algorithm:

image

Demonstrate an example:

imageimage

image

image

*Source code*:

Give a ghaph:

imageInput file:

image 

Code:

#include <cstdlib>
#include <iostream>
#include <fstream>

using namespace std;

ifstream fi("FLOYD.INP");
ofstream fo("FLOYD.OUT");

int n,m;//n is number of vertex, m is number of edge
int const MAX = 1000;
int const vc = 32000;//infinite value
int w[MAX][MAX], d[MAX][MAX], p[MAX][MAX];//array of distance and parent

//print function: call itseft to retrieve node and print the node
void print_path (int i, int j)
{
    if( i!=j) {print_path(i,p[i][j]);}
    cout<<j<<" ";
}
int main(int argc, char *argv[])
{  
    fi>>n>>m;
    //Input
    int d1,d2,temp;
    for( int i = 0; i < m; i++)
    {       
        fi>>d1>>d2>>temp;
        w[d1][d2] = temp;
    }
    //Initialization
    cout<<"Initial array:"<<endl;
    for( int i=1; i<=n; i++)
    {
        for( int j = 1; j <= n; j++)
        {        
             //assign distance and parent array
             if( w[i][j] != 0) d[i][j] = w[i][j];            
             else  d[i][j] = vc;// ! Very important
             p[i][j] = i;//init parent of each node
             cout<<d[i][j]<<" ";            
        }cout<<endl;
    }cout<<endl;
    for( int i=1; i<=n; i++) d[i][i] = 0;
    cout<<"Optimize distance gradually"<<endl;
    for( int k=1;k<=n;k++)//loop for intermediate vertex
    {
        for( int i=1;i<=n;i++)//loop for start vertex
        {
            for( int j=1;j<=n;j++)//loop for end vertex
            {
                if( d[i][k] != 0 && d[k][j] != 0 &&d[i][k] + d[k][j] < d[i][j])
                {
                   d[i][j] = d[i][k]+d[k][j];cout<<i<<" "<<k<<" "<<j<<" "<<d[i][j]<<endl;
                   //update parent of end vertex
                   p[i][j] = p[k][j];   cout<<p[i][j]<<endl;                              
                }
            }
         }
    }
    //Print the result for review
    cout<<"Result of distance array:"<<endl;
    for( int i=1; i<=n; i++)
    {
        for( int j=1; j<=n; j++)
        {
            cout<<d[i][j]<<" ";
        }cout<<endl;
    } cout<<endl;
    cout<<"Result of parent array:"<<endl;
    for( int i=1; i<=n; i++)
    {
        for( int j=1; j<=n; j++)
        {
            cout<<p[i][j]<<" ";
        }cout<<endl;
    } cout<<endl;
    //Output
    int start_vertex = 1, end_vertex = 4;    
    if( d[start_vertex][end_vertex] < vc)
    {
        cout<<"Shortest distance from "<<start_vertex<<" to "<<end_vertex<<" is: ";
        cout<<d[start_vertex][end_vertex]<<endl;
        cout<<"Through vertexs: ";
        print_path(start_vertex,end_vertex); 
        cout<<endl;
    }
    else cout<<"No path from "<<start_vertex<<" to "<<end_vertex<<endl;
    system("PAUSE");
    return EXIT_SUCCESS;
}

Output Screen:

image

The end! Hope you successful.

Categories: Algorithm

Apply Dynamic Programming in LIS (Longest Inc Subsequence)

November 17, 2012 Leave a comment

Input: Given a sequence
Output: The longest subsequence of the given sequence such that all values in this
longest subsequence is strictly increasing.

Input:

image

Output:

image

Code:

#include <cstdlib>
#include <iostream>
#include <fstream>

using namespace std;

ifstream fi("LIS.INP");
ofstream fo("LIS.OUT");

int main(int argc, char *argv[])
{
    int n;// string length
    int height[1000];//given array
    int length[1000] = {1};//array that record the max length
    int predecessor[1000] = {-1}; //the array that mark the parent of node
    //Input
    fi>>n;
    for( int i = 0; i < n; i++)
    {
         fi>>height[i];
     }
     //using dynamic programming
     for( int i = 0; i < n – 1; i++)
     {
          for( int j = i + 1; j < n; j++)  
          {
               if( height[j] > height[i])
               {
                   if( length[i] + 1 > length[j])
                   {
                       length[j] = length[i] + 1;
                       predecessor[j] = i;                 
                   }
               }
           }
     }
     //Output
     int max = length[0];
     for( int i = 1; i < n; i++)
     {
          if( length[i] > max) max = length[i];
     }
     fo<<max<<endl;
    system("PAUSE");
    return EXIT_SUCCESS;
}

Categories: Algorithm

LINQ to Entities – Thời đại mới của LINQ


Giới thiệu:

Trong khi bộ VS 2008 vẫn chưa có LINQ to Entities thì trong phiên bản VS 2010, LINQ to Entities đã được bổ sung thêm và trở thành một bộ phận rất nổi trội tham gia vào gia đình LINQ với những tính năng mới hơn so với đàn anh đi trước. Tuy nhiên, LINQ to Entities hoạt động trên Entities Framework còn đàn anh của nó thì trên LINQ Framework. LINQ to Entities có tính mềm dẻo và khá mạnh mẽ vì:

– Thể hiện được mô hình thực thể, giống như mô hình ý niệm của dữ liệu

– Binging cơ sở dữ liệu vật lý, hỗ trợ các phương thức giống với LINQ to SQL

– Bổ sung một số khái niệm mới như strong-typing, đa hình, kiểu phức hợp, …

Nhập môn LINQ to Entities:

Sử dụng LINQ to Entities thông qua ví dụ đơn giản sau:

Ví dụ này chỉ việc load bảng lên GridView bằng LINQ to Entities, còn các phương thức thêm, xóa, sửa thì gần giống LINQ to SQL nên không đề cập đến. Việc sử dụng Stored Procedure thì hơi khác sẽ được đề cập trong những bài viết tiếp theo.

-Tạo project WPF

image

-Tại project add New Item> mục Data > Chọn ADO.NET Entity Data Model

image

Read more…

Categories: Database, LINQ
Design a site like this with WordPress.com
Get started