Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Saturday, 21 January 2017

Tuesday, 24 May 2016

c# node.selectnodes add attribute

   Item objItem = _inn.newItem("Identity", "get");
            Item logicItm = objItem.newOR();

            logicItm.setProperty("name", "%Admin%");
            logicItm.setProperty("name", "%Author%");

            Item iChildren = objItem.getLogicalChildren();
            for (int i = 0; i < iChildren.getItemCount(); i++)
            {
                Item iChild = iChildren.getItemByIndex(i);
   
                XmlDocument objXDoc = new XmlDocument();
                XmlAttribute objNewAtt = objXDoc.CreateAttribute("condition");
                objNewAtt.Value = "like";

                XmlNodeList allNames = iChild.node.SelectNodes("name");
                foreach (XmlNode eachName in allNames)
                {
                    eachName.Attributes.SetNamedItem(objNewAtt);
                }

            }
            Item retItm = objItem.apply();

Wednesday, 6 April 2016

C# How to convert WSDL to SVC



Assuming you are having .wsdl file at location "E:\" for ease in access further.
Prepare the command for each .wsdl file as: E:\YourServiceFileName.wsdl
Permissions: Assuming you are having the Administrative rights to perform permissions. Open directory : C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin
Right click to amd64 => Security => Edit => Add User => Everyone Or Current User => Allow all permissions => OK.
Prepare the Commands for each file in text editor as: wsdl.exe E:\YourServiceFileName.wsdl /l:CS /server.
Now open Visual studio command prompt from : C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts\VS2013 x64 Native Tools Command Prompt.
Execute above command.
Go to directory : C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\amd64, Where respective .CS file should be generated.
Move generated CS file to appropriate location.

Thursday, 24 March 2016

c# nested dictionary foreach key value pair

 Dictionary<string, Dictionary<string, string>> objData = new Dictionary<string, Dictionary<string, string>>();

//Assign data to  nested dictionary
                        objData.Add("A1", new Dictionary<string, string>() { { "motor1", "A1" } });
                        objData["A1"].Add("motor2", "A2");
                        objData["A1"].Add("motor3", "A3");

                        objData.Add("B1", new Dictionary<string, string>() { { "motorb1", "B1" } });
                        objData["B1"].Add("motorb2", "B2");
                        objData["B1"].Add("motorb3", "B3");


//Read data from  nested dictionary
                        foreach (var outerDict in objData)
                        {
                            var innerDict = outerDict.Value;

                            foreach (var innerDictValue in innerDict)
                            {
                                Console.WriteLine(outerDict.Key + " " + innerDictValue.Key + " " + innerDictValue.Value);
                            }
                        }

Wednesday, 30 September 2015

how to remove empty line when reading text file using C#



IEnumerable<string> lines = File.ReadLines().Where(line => line != "");

or

List<string> lines = File.ReadLines().Where(line => line != "").ToList();

Sunday, 1 March 2015

C# string replace with escape characters



Input argumenets
#to=test@gmail.com #subject="Welcome to" #server=mail.gmail.com #port=8080 #from=from@gmail.com

#to="test@gmail.com" #subject="Welcome" #server="mail.gmail.com" #port="8080" #from="from@gmail.com"

#to=\"test@gmail.com\" #subject=\"Welcome\" #server=\"mail.gmail.com\" #port=\"8080\" #from=\"from@gmail.com\"

Expected input string to application.
#to=\"test@gmail.com\" #subject=\"Welcome\" #server=\"mail.gmail.com\" #port=\"8080\" #from=\"from@gmail.com\"

Application will get Input argumenets in any format of give 3 type, but business will work for only one type of format, so we have to manipulate rest of the 2 types to 3rd type.

Solution:
I am going to write one exe, to manipulate input args.
Open Visual studio
Create new console project: StringEscapeCharacters
Open: Program.cs file

Please find my code...


Now i have to pass arguments to my exe, i can to multiple ways..
1st way: Open solution explorer, right click on project.
Click on: Properties
Click on: Debug
Under Start Options:
Command line arguments: <Enter arguments>
Ex:
#to=test@gmail.com #subject="Welcome to exe" #server=mail.gmail.com #port=8080 #from=from@gmail.com


You will get out put as in the log file:C:\Temp\mylog.log
#to="test@gmail.com" #subject="Welcome to exe" #server="mail.gmail.com" #port="8080" #from="from@gmail.com"

2nd way passing args:
Build the application.
now go to bin/debug folder,
you will see: StringEscapeCharacters.exe
execute this exe from cmd and pass args.
ex: StringEscapeCharacters.exe #to=test@gmail.com #subject="Welcome to exe" #server=mail.gmail.com #port=8080 #from=from@gmail.com

Sunday, 13 July 2014

C# ListView

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace ListV
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
#region Working
DataTable table = new DataTable();
table.Columns.Add("MainGroup", typeof(string));
table.Columns.Add("Subject", typeof(string));
table.Rows.Add("Class A", "English");
table.Rows.Add("Class B", "Science");
table.Rows.Add("Class C", "Hindi");
table.Rows.Add("Class B", "Computers");
table.Rows.Add("Class C", "Maths");
//GridView1.DataSource = table;
//GridView1.DataBind();
#endregion
if (!IsPostBack)
{
try
{
DataTable dt = new DataTable();
dt = table;
DataTable dydt = new DataTable("test");
string test = string.Empty;
foreach (DataRow myRow in dt.Rows)
{
foreach (DataColumn myCol in dt.Columns)
{
if (myCol.ColumnName.ToString() == "MainGroup")
{
if (!dydt.Columns.Contains(myRow[myCol].ToString()))
{
dydt.Columns.Add(myRow[myCol].ToString(), typeof(System.String));
}
}
}
}
foreach (DataRow myRow in dt.Rows)
{
string strSubject = myRow["Subject"].ToString();
foreach (DataColumn myCol in dt.Columns)
{
if (myCol.ColumnName.ToString() == "MainGroup")
{
string strMainGroup = myRow[myCol].ToString();
foreach (DataColumn myfinalCol in dydt.Columns)
{
if (myfinalCol.ColumnName.ToString().Trim() == strMainGroup)
{
DataRow row;
row = dydt.NewRow();
row[strMainGroup] = strSubject;
dydt.Rows.Add(row);
}
}
}
}
}
GridView1.DataSource = dydt;
GridView1.DataBind();
}
catch (Exception ex)
{
lblError.Visible = true;
lblError.Text = "Error" + ex.StackTrace + "Message: " + ex.Message;
}
}
}
}
}
ListView

Tuesday, 29 April 2014

C# Generics Demo

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
//using System.Web;
//using System.Web.Security;
//using System.Web.UI;
//using System.Web.UI.WebControls;
//using System.Web.UI.WebControls.WebParts;
//using System.Web.UI.HtmlControls;
public partial class GenericsDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Student dhas = new Student("Manick", "Dhas", 22);
Student raj = new Student("Sundar", "Raj", 32);
///Using a custom strongly typed StudentList
StudentList mc = new StudentList();
mc.Add(dhas);
mc.Add(raj);
Response.Write("Using a custom strongly typed StudentList
");
foreach (Student s in mc)
{
Response.Write("First Name : " + s.FirstName + "
");
Response.Write("Last Name : " + s.LastName + "
");
Response.Write("Age : " + s.Age + "

");
}
///Creating a list of Student objects using my custom generics
MyCustomList student = new MyCustomList();
student.Add(dhas);
student.Add(raj);
Response.Write("
Using a list of Student objects using my custom generics
");
foreach (Student s in student)
{
Response.Write("First Name : " + s.FirstName + "
");
Response.Write("Last Name : " + s.LastName + "
");
Response.Write("Age : " + s.Age + "

");
}
///Creating a list of Student objects using my custom generics
MyCustomList intlist = new MyCustomList();
intlist.Add(1);
intlist.Add(2);
Response.Write("
Using a list of String values using my custom generics
");
foreach (int i in intlist)
{
Response.Write("Index : " + i.ToString() + "
");
}
///Creating a list of Student objects using my custom generics
MyCustomList strlist = new MyCustomList();
strlist.Add("One");
strlist.Add("Two");
Response.Write("
Using a list of int values using my custom generics
");
foreach (string str in strlist)
{
Response.Write("Index : " + str + "
");
}
}
}
///
/// Student Class
///
public class Student
{
private string fname;
private string lname;
private int age;
///
/// First Name Of The Student
///
public string FirstName
{
get { return fname; }
set { fname = value; }
}
///
/// Last Name Of The Student
///
public string LastName
{
get { return lname; }
set { lname = value; }
}
///
/// Age of The Student
///
public int Age
{
get { return age; }
set { age = value; }
}
///
/// Creates new Instance Of Student
///
/// FirstName
/// LastName
/// Age
public Student(string fname, string lname, int age)
{
FirstName = fname;
LastName = lname;
Age = age;
}
}
///
/// Strongly Typed Class
/// Accepts only Student Type
///
public class StudentList : IEnumerable
{
private ArrayList alist = new ArrayList();
///
/// Adds new value of type Student
///
/// Object of Student Class
/// Returns the index of the Object
public int Add(Student value)
{
try
{
return alist.Add(value);
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Removes The Object from StudentList
///
/// Object of Student Class
public void Remove(Student value)
{
try
{
alist.Remove(value);
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Removes the student object
///
/// Index of the Student object to be removed
public void RemoveAt(int index)
{
try
{
alist.RemoveAt(index);
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Gets the count of the StudentList
///
public int Count
{
get { return alist.Count; }
}
#region IEnumerable Members
///
/// Returns an enumerator that iterates through a StudentList.
///
/// An System.Collections.IEnumerator object that can be used to iterate through the StudentList
public IEnumerator GetEnumerator()
{
try
{
return alist.GetEnumerator();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
}
///
/// Custom Generic Accepts any Types
///
///
public class MyCustomList : IEnumerable, IEnumerable
{
private ArrayList alist = new ArrayList();
///
/// Adds new value of type T
///
/// Object of Type T
/// Returns the index
public int Add(T value)
{
try
{
return alist.Add(value);
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Removes The Object from MyCustomList
///
/// Object of Type T
public void Remove(T value)
{
try
{
alist.Remove(value);
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Removes the object at index
///
/// Index of the T object to be removed
public void RemoveAt(int index)
{
try
{
alist.RemoveAt(index);
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Gets the count of the MyCustomList Object
///
public int Count
{
get { return alist.Count; }
}
#region IEnumerable Members
///
/// Returns an enumerator that iterates through a collection.
///
/// An System.Collections.IEnumerator object that can be used to iterate through the collection
public IEnumerator GetEnumerator()
{
try
{
return alist.GetEnumerator();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region IEnumerable Members
///
/// Returns an enumerator that iterates through a collection.
///
/// An System.Collections.IEnumerator object that can be used to iterate through the collection
IEnumerator IEnumerable.GetEnumerator()
{
try
{
return (IEnumerator)alist.GetEnumerator();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
}

Monday, 28 April 2014

C# Dictionary

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
namespace Test_N.G
{
public partial class A : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Author A1 = new Author(TextBox1.Text, TextBox2.Text, "AAA", "123-4567");
Author A2 = new Author("TTT", "B", "BBB", "123-7823");
Author A3 = new Author("MS", "C", "CCC", "123-6383");
Dictionary dict = new Dictionary();
dict.Add(A1.Id, A1);
dict.Add(A2.Id, A2);
dict.Add(A3.Id, A3);
lboxDictionary.DataSource = dict;
lboxDictionary.DataBind();
ReadDic(dict);
}
protected void ReadDic(Dictionary dict)
{
//Read Dictionary
string strToEmail = string.Empty;
HashSet setUniqEmail = new HashSet();
foreach (KeyValuePair kv in dict)
{
Author au = kv.Value;
strToEmail += au.AuthorName + ",";
}
string[] sArray = strToEmail.Split(',');
HashSet set = new HashSet(sArray);
string[] result = new string[set.Count];
set.CopyTo(result);
//setUniqEmail = set;
foreach (string i in set)
{
string strBody = string.Empty;
foreach (KeyValuePair kv in dict)
{
Author au = kv.Value;
if ((i != null) & (i != ""))
{
if (i == au.AuthorName)
{
strBody += au.Id + "-" + au.ItemURL + "-" + au.AuthorName + "-" + au.searchKeyWord + System.Environment.NewLine;
}
}
}
Response.Write(strBody);
}
}
}
public abstract class AAbstractEntity
{
private string _id;
public AAbstractEntity(string id)
{
_id = id;
}
public string Id
{
get { return _id; }
set { _id = value; }
}
public abstract bool IsValid
{
get;
}
}
public class Author : AAbstractEntity
{
private string _ItemURL;
private string _AuthorName;
private string _searchKeyWord;
public Author(string id, string ItemURL, string AuthorName, string searchKeyWord)
: base(id)
{
_ItemURL = ItemURL;
_AuthorName = AuthorName;
_searchKeyWord = searchKeyWord;
}
public string ItemURL
{
get { return _ItemURL; }
set { _ItemURL = value; }
}
public string AuthorName
{
get { return _AuthorName; }
set { _AuthorName = value; }
}
public string searchKeyWord
{
get { return _searchKeyWord; }
set { _searchKeyWord = value; }
}
public override bool IsValid
{
get
{
if (Id.Length > 0 && AuthorName.Length > 0)
return true;
else
return false;
}
}
public override string ToString()
{
return Id + "," + AuthorName + ", " + ItemURL + "," + searchKeyWord;
}
}
}

C# Collection Custom Order Display

C# Collection Custom Order Display
Collection filter = new Collection();
//filter=Coming from External Source with different order Date is: S,O,M,C,I,R
//Now i have to change the order of filter based on some custom condition.
//I am going to take new collection with name:afterfilColl
Collection afterfilColl = new Collection();
if (filter.Items.Count != 0)
{
int countno = 8;
if (filter.Items.Count > 8)
{
countno = filter.Items.Count;
}
for (int i = 0; i < countno; i++)
{
afterfilColl.Insert(i, null);
}
}
int j = 0;
for (int i = 0; i < filter.Items.Count; i++)
{
if (filter.Items[i].Name == "M")
{
afterfilColl.RemoveAt(0);
afterfilColl.Insert(0, filter.Items[i]);
}
else if (filter.Items[i].Name == "I")
{
afterfilColl.RemoveAt(1);
afterfilColl.Insert(1, filter.Items[i]);
}
else if (filter.Items[i].Name == "C")
{
afterfilColl.RemoveAt(2);
afterfilColl.Insert(2, filter.Items[i]);
}
else if (filter.Items[i].Name == "R")
{
afterfilColl.RemoveAt(3);
afterfilColl.Insert(3, filter.Items[i]);
}
else if (filter.Items[i].Name == "O")
{
afterfilColl.RemoveAt(5);
afterfilColl.Insert(5, filter.Items[i]);
}
else if (filter.Items[i].Name == "S")
{
afterfilColl.RemoveAt(7);
afterfilColl.Insert(7, filter.Items[i]);
}
else
{
afterfilColl.Insert(j + 8, filter.Items[i]);
j++;
}
}
filter.Items.Clear();
for (int i = 0; i < afterfilColl.Count; i++)
{
if (afterfilColl[i] != null)
{
filter.Items.Add(afterfilColl[i]);
}
}
//Now i will get date in to filter collection with order of M,I,C,R,O,S

Wednesday, 12 March 2014

How to get file length in C#

How to get file length in C#
using System;
using System.IO;
class GetFileLength
{
static void Main()
{
const string strFileName = "Myfile.txt";
FileInfo objfileInfo = new FileInfo(strFileName);
long s1 = objfileInfo.Length;
File.AppendAllText(strFileName, " Add new information....");
FileInfo f2 = new FileInfo(strFileName);
long s2 = f2.Length;
Console.WriteLine("Before and after: " + s1.ToString() + "" + s2.ToString());
long change = s2 - s1;
Console.WriteLine("Size increase: " + change.ToString());
}
}