C# create configuration file - c#-4.0

This code How can I create configuration file if so that i can change connection string easy
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Web;
using mshtml;
namespace tabcontrolweb
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string MyConString = "SERVER=192.168.0.78;" +
"DATABASE=webboard;" +
"UID=aimja;" +
"PASSWORD=aimjawork;" +
"charset=utf8;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "SELECT urlwebboard FROM `listweb` WHERE `urlwebboard` IS NOT NULL AND ( `webbordkind` = 'เว็บท้องถิ่น' ) and `nourl`= 'n' order by province, amphore limit 4 ";
connection.Open();
Reader = command.ExecuteReader();
string[] urls = new string[4];
string thisrow = "";
string sumthisrow = "";
while (Reader.Read())
{
thisrow = "";
for (int i = 0; i < Reader.FieldCount; i++)
{
thisrow += Reader.GetValue(i).ToString();
System.IO.File.AppendAllText(#"C:\file.txt", thisrow + " " + Environment.NewLine);
sumthisrow = Reader.GetValue(Reader.FieldCount - 1).ToString();
}
for (int m = 0; m < 4 ; m++)
{
urls[m] = sumthisrow;
MessageBox.Show(urls[m]);
}
webBrowser1.Navigate(new Uri(urls[0]));
webBrowser1.Dock = DockStyle.Fill;
webBrowser2.Navigate(new Uri(urls[1]));
webBrowser2.Dock = DockStyle.Fill;
webBrowser3.Navigate(new Uri(urls[2]));
webBrowser3.Dock = DockStyle.Fill;
webBrowser4.Navigate(new Uri(urls[3]));
webBrowser4.Dock = DockStyle.Fill;
}
connection.Close();
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//if (webBrowser1.Document != null)
//{
// IHTMLDocument2 document = webBrowser1.Document.DomDocument as IHTMLDocument2;
// if (document != null)
// {
// IHTMLSelectionObject currentSelection = document.selection;
// IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange;
// if (range != null)
// {
// const String search = "We";
// if (range.findText(search, search.Length, 2))
// {
// range.select();
// }
// }
// }
//}
}
}
}

You can create an XML configuration file looking like this :
<db-config>
<server>192.168.0.78</server>
<database>webboard</database>
<...>...</...>
</db-config>
Then, use XMLTextReader to parse it.
Here is a basic example of how you can use it to parse XML files :
using System;
using System.Xml;
namespace ReadXMLfromFile
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static void Main(string[] args)
{
XmlTextReader reader = new XmlTextReader ("books.xml");
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
Console.Write("<" + reader.Name);
Console.WriteLine(">");
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine (reader.Value);
break;
case XmlNodeType.EndElement: //Display the end of the element.
Console.Write("</" + reader.Name);
Console.WriteLine(">");
break;
}
}
Console.ReadLine();
}
}
}
Hint : Use the ReadTofollowing() to get your values.
Once your XML DB Config Reader class is done, you use it each time you need a new connection, and you'll only need to change your DB Config XML file to change your DB Connections configuration.
Edit : there is an interesting article about Storing database connection settings in .NET here.

Use the default
System.Configuration.ConfigurationManager
that C# supports!

See: http://msdn.microsoft.com/en-us/library/bb397750.aspx

Related

review comport code in wince 6.0

hellou all, we have ibutton devices for reading ibutton. This device is usb and have FTDI virtual comport.
We have our simple aplication for reading data from reader, but reader have problem (when is more buttons swipe on reader - it stop send data)
In this case when we catch problem (sending G and g - like green diode stop and start), restart comport - but after reboot comport aplication takes 100% of cpu.
is here anybody which have any idea what we need to do or how modify source code.
thanks a lot
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using OpenNETCF;
namespace SerialDownload
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
AddLog("Vytvaram novy seriovy port");
serialPort1 = new System.IO.Ports.SerialPort();
serialPort1.PortName = "COM4";
serialPort1.Handshake = System.IO.Ports.Handshake.None;
serialPort1.DataReceived += serialPort1_DataReceived;
//serialPort1.ErrorReceived += new System.IO.Ports.SerialErrorReceivedEventHandler(serialPort1_ErrorReceived);
//serialPort1.PinChanged += new System.IO.Ports.SerialPinChangedEventHandler(serialPort1_PinChanged);
serialPort1.WriteBufferSize = 10000;
serialPort1.RtsEnable = true;
serialPort1.DtrEnable = true;
serialPort1.ReadTimeout = 2000;
serialPort1.WriteTimeout = 2000;
AddLog("Vytvoreny seriovy port");
}
bool zelena = false;
private void timerResetCOM_Tick(object sender, EventArgs e)
{
timerResetCOM.Enabled = false;
if (!nacitavam_kartu_serial)
{
try
{
string znak = "G";
if (!zelena)
{
znak = "g";
zelena = true;
}
else
{
zelena = false;
}
AddLog("Posielam " + znak);
serialPort1.WriteTimeout = 2000;
serialPort1.Write(znak);
System.Threading.Thread.Sleep(200);
AddLog("Odoslane " + znak);
}
catch
{
System.Threading.Thread.Sleep(200);
AddLog("Chyba serioveho portu pri odoslani G");
try
{
serialPort1.DataReceived -= serialPort1_DataReceived;
AddLog("robim discard");
serialPort1.DiscardOutBuffer();
System.Threading.Thread.Sleep(200);
AddLog("Discard dokonceny");
AddLog("Zatvaram port");
serialPort1.Close();
AddLog("port zatvoreny");
KillProc("SerialDownload");
}
catch
{
System.Threading.Thread.Sleep(200);
AddLog("Chyba zatorenia portu");
}
/*
try
{
AddLog("Dispose serioveho");
serialPort1.DataReceived -= serialPort1_DataReceived;
serialPort1.Dispose();
System.Threading.Thread.Sleep(200);
AddLog("Dispose serioveho OK");
AddLog("Vytvaram novy seriovy port");
serialPort1 = new System.IO.Ports.SerialPort();
serialPort1.PortName = "COM4";
serialPort1.Handshake = System.IO.Ports.Handshake.None;
serialPort1.DataReceived += serialPort1_DataReceived;
//serialPort1.ErrorReceived += new System.IO.Ports.SerialErrorReceivedEventHandler(serialPort1_ErrorReceived);
//serialPort1.PinChanged += new System.IO.Ports.SerialPinChangedEventHandler(serialPort1_PinChanged);
serialPort1.WriteBufferSize = 10000;
serialPort1.RtsEnable = true;
serialPort1.DtrEnable = true;
serialPort1.ReadTimeout = 2000;
serialPort1.WriteTimeout = 2000;
AddLog("Vytvoreny seriovy port");
}
catch (Exception ex)
{
AddLog("Chyba vytvaranie serioveho portu - alebo rusenia");
}
System.Threading.Thread.Sleep(1000);
try
{
AddLog("otvaram port");
serialPort1.Open();
serialPort1.RtsEnable = true;
serialPort1.DtrEnable = true;
serialPort1.ReadTimeout = 2000;
serialPort1.WriteTimeout = 2000;
AddLog("port otvoreny");
}
catch
{
System.Threading.Thread.Sleep(200);
AddLog("Chyba otvorenia portu");
}*/
}
}
}
bool nacitavam_kartu_serial = false;
private void KillProc(string name)
{
var processes = OpenNETCF.ToolHelp.ProcessEntry.GetProcesses();
foreach (OpenNETCF.ToolHelp.ProcessEntry process in processes)
{
if (name == process.ExeFile)
{
process.Kill();
}
}
}
private void AddLog(string riadok)
{
Debug.WriteLine(DateTime.Now.ToString("yyyy-mm-dd HH:mm:ss") + ": " + riadok);
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
nacitavam_kartu_serial = true;
AddLog("Nacitacam data");
try
{
string pStrTmp = string.Empty;
while (serialPort1.BytesToRead > 0)
{
pStrTmp += (char)serialPort1.ReadByte();
System.Threading.Thread.Sleep(15);
}
string card_id_t = pStrTmp;
AddLog("Nacitane data: " + card_id_t);
StreamWriter subor = File.CreateText("\\NAND\\karta_serial.txt");
subor.Write(card_id_t);
subor.Close();
}
catch (Exception ex)
{
AddLog(ex.Message);
}
nacitavam_kartu_serial = false;
}
}
}
It is late, but I will leave my answer here.
I have seen similar problem with .NET Compact Framework and com port, two years ago. The device I had was on windows mobile 6, the other device was BT printer on comport.
Other handheld devices ran just fine, just this one had exactly the same problem, when you turn of the printer - the app ran slow, to the point where you could not use it for work anymore.
My temporal solution was to close the SerialPort object.
I hope it helps

More webrequest in a text file

I have this:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class Program
{
static void Main(string[] args)
{
//Consider making this configurable
const string sourceFile = "testSolar.txt";
const string pattern = "http://10.123.9.66:80";
Regex re = new Regex("^(http|https)://");
//var res = re.Match(str);
var webClient = new WebClient();
var times = new Dictionary<string, TimeSpan>();
var stopwatch = new System.Diagnostics.Stopwatch();
//Add header so if headers are tracked, it will show it is your application rather than something ambiguous
webClient.Headers.Add(HttpRequestHeader.UserAgent, "Response-Tester-Client");
var urlList = new List<string>();
//Loop through the lines in the file to get the urls
try
{
stopwatch.Start();
using (var reader = new StreamReader(sourceFile))
{
while (!reader.EndOfStream)
{
var urNewList = new List<string>();
var line = reader.ReadLine();
//line = line.Substring(line.IndexOf(pattern));
//line.Split("\t");
var columns = line.Split('\t');
if (columns[2] == "R")
{
var url = columns[4] + "?" + columns[5];
urlList.Add(url);
}
}
}
}
catch (Exception e)
{
Console.WriteLine("An error occured while attempting to access the source file at {0}", sourceFile);
}
finally
{
//Stop, record and reset the stopwatch
stopwatch.Stop();
times.Add("FileReadTime", stopwatch.Elapsed);
stopwatch.Reset();
}
//Try to connect to each url
var counter = 1;
foreach (var url in urlList)
{
try
{
stopwatch.Start();
webClient.DownloadString(url);
}
catch (Exception e)
{
Console.WriteLine("An error occured while attempting to connect to {0}", url);
}
finally
{
stopwatch.Stop();
//We use the counter for a friendlier url as the current ones are unwieldly
times.Add("Url " + counter, stopwatch.Elapsed);
counter++;
stopwatch.Reset();
}
}
//Release the resources for the WebClient
webClient.Dispose();
//Write the response times
foreach (var key in times.Keys)
{
Console.WriteLine("{0}: {1}", key, times[key].TotalSeconds);
}
Console.ReadKey();
}
}
}
And I have three lines in a text file, like this:
2014-08-25 14:20:43,949 DEV belkbyavlahok0jrvoutn2xd 21 R O http://10.123.9.66:80/solr_3.6/wiewaswie_live/select/ qt=standard_a2aperson&q=*:*&fq=(nosyn_name_last_exact:(qxqroelofqxq))&fq=(nosyn_name_patronym_exact:(qxqharmsqxq))&spellcheck.q=(qxqroelofqxq qxqharmsqxq)&fq={!tag%3Dalldoctypes}doc_type:1&fq=date_main:[0 TO 18133112]&facet.query={!ex%3Dalldoctypes}doc_type:3 AND (b_public:1)&facet.query={!ex%3Dalldoctypes}doc_type:2 AND (b_public:1)&spellcheck=true&spellcheck.count=-3&start=0&sort=name_last asc, score desc&omitHeader=true
2014-08-25 14:20:45,478 DEV z5gyjtcexs41vra4yegqejcf 0 R . http://10.123.9.66:80/solr_3.6/combi_live/select/ qt=standard_a2aperson&q=(((((nosyn_name_last_b_exact:(qxqkuilenburgqxq))))))&fq=(nosyn_name_last_exact:(qxqbroekqxq))&spellcheck.q=(qxqbroekqxq kuilenburg)&fq=(fk_collectiontype:6)&spellcheck=true&spellcheck.count=-3&start=10&sort=date_main asc, score desc&omitHeader=true
2014-08-25 14:20:45,930 DEV hmb0uqzc10s0ounwdhpwmflp 1 R O http://10.123.9.66:80/solr_3.6/combi_live/select/ qt=standard_a2aperson&q=(((((nosyn_name_last_b_exact:(qxqkruijsqxq))))))&fq=(nosyn_name_first_exact:(qxqw*qxq))&fq=(nosyn_name_last_exact:(qxqtreurenqxq))&spellcheck.q=(qxqw*qxq qxqtreurenqxq kruijs)&spellcheck=true&spellcheck.count=-3&start=0&sort=date_main asc, score desc&omitHeader=true
But if I just have 1 line, like this:
2014-08-25 14:20:45,930 DEV hmb0uqzc10s0ounwdhpwmflp 1 R O http://10.123.9.66:80/solr_3.6/combi_live/select/ qt=standard_a2aperson&q=(((((nosyn_name_last_b_exact:(qxqkruijsqxq))))))&fq=(nosyn_name_first_exact:(qxqw*qxq))&fq=(nosyn_name_last_exact:(qxqtreurenqxq))&spellcheck.q=(qxqw*qxq qxqtreurenqxq kruijs)&spellcheck=true&spellcheck.count=-3&start=0&sort=date_main asc, score desc&omitHeader=true
then it works, but if I have more then I get an
The remote server returned an error: (404) Not Found.
Thank you for you help

Trying to download all URL's in html

Can anybody help me with this code?
I am trying to download all the URL's in this html http://mises.org/books/ (they are all pdf's )
I understand the basic logic, I think I just am messing up the regular expression. This is what I have so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
namespace DownloadPdfs
{
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("http://mises.org/books/");
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0); // any more data to read?
string html = sb.ToString();
List<string> listoflinks = new List<string>();
string input = html;
Regex rx = new Regex(#"(?<="")[^""]+(?="")|[^\s""]\S*");
for (Match match = rx.Match(input); match.Success; match = match.NextMatch())
{
listoflinks.Add(match.ToString());
}
foreach (var v in listoflinks)
{
using (WebClient Client = new WebClient())
{
Client.DownloadFile(v,v);
}
}
}
}
}
Try the code below. The pattern will match the value of HREF attribute for anchors.
Regex rx = new Regex(#"href=""(?<Url>[^.""]+\.pdf)""",RegexOptions.IgnoreCase | RegexOptions.Multiline);
for (Match match = rx.Match(input); match.Success; match = match.NextMatch())
{
var link = match.Groups["Url"].Value;
listoflinks.Add(link);
}
Use a library to parse html like HtmlAgilityPack.
public List<string> GetLinks(string html)
{
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
var linkNodes = htmlDoc.DocumentNode.SelectNodes("//a[#href]");
if (linkNodes == null)
{
return new List<string>();
}
var linkNodesWithLink = linkNodes.Where(x => x.Attributes.Contains("href")).ToList();
var links = linkNodesWithLink.Select(x => x.Attributes["href"].Value)
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => x.Trim())
.ToList();
links = links.Distinct().ToList();
return links;
}

Selected Item getting lost on post back (Sharepoint wss3.0 webpart)

I am new Sharepoint developer and trying to create search webpart in window Sharepoint service 3.0 [Free edition], so far I can select multiple item from list box but when i trying to display selected item into textbox it getting lost.
Below is my code:
using System;
using System.Runtime.InteropServices;
using System.Data;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Xml.Serialization;
using System.Collections;
namespace Filter_WebPart
{
[Guid("6641a7a3-d2c4-4fda-9ef5-89596845bd6e")]
public class Filter_WebPart : System.Web.UI.WebControls.WebParts.WebPart
{
protected DataSet _dataset;
protected ListBox lstRegion;
protected ListBox lstMaterial;
protected HtmlButton btnSubmit;
protected HtmlInputText txtDisplay;
private string myExceptions = "";
//private int[] Index1;
protected override void CreateChildControls()
{
try
{
//Region Table / DataSet
lstRegion = new ListBox();
lstRegion.ID="lstRegion";
lstRegion.SelectionMode = ListSelectionMode.Multiple;
//lstRegion.EnableViewState = true;
//lstRegion.SelectedIndex = 0;
//Material Table / DataSet
lstMaterial = new ListBox();
lstMaterial.SelectionMode = ListSelectionMode.Multiple;
lstMaterial.EnableViewState = true;
btnSubmit = new HtmlButton();
btnSubmit.InnerText = "Filter";
btnSubmit.ServerClick += new EventHandler(btnSubmit_Click);
txtDisplay = new HtmlInputText();
//CommandButton
this.Controls.Add(lstRegion);
this.Controls.Add(lstMaterial);
this.Controls.Add(btnSubmit);
this.Controls.Add(txtDisplay);
}
catch(Exception ChildControlException)
{
myExceptions += "ChildControlException:" + ChildControlException.Message;
}
finally
{
//base.CreateChildControls();
}
}
protected override void OnPreRender(EventArgs e)
{
if(!this.Page.IsPostBack)
{
lstMaterial.DataSource = GetMaterialList();
lstMaterial.DataTextField = "Material Name";
lstMaterial.DataValueField = "Material Name";
lstMaterial.DataBind();
lstRegion.DataSource = GetRegionList();
lstRegion.DataTextField = "Region Name";
lstRegion.DataValueField = "Region Name";
lstRegion.DataBind();
txtDisplay.Value="1 time";
}
base.OnPreRender(e);
}
void btnSubmit_Click(object sender, EventArgs e)
{
string tmpStr="";
int k=0;
//int i=0;
lstMaterial.DataBind();
lstRegion.DataBind();
//int[] indx = lstRegion.GetSelectedIndices();
//for(i=0;i<indx.Length;i++)
//{
// tmpStr = tmpStr+","+lstRegion.Items[indx[i]].Text;
//}
//if(lstRegion.SelectedIndex >=0 )
//{
//for(i=0;i < lstRegion.Items.Count;i++)
//{
// //if(i==5 || i==10)
// //{
// // lstRegion.Items[i].Selected = true;
// //}
// if(lstRegion.Items[i].Selected)
// {
// tmpStr = lstRegion.Items[i].Text;
// }
// k=k+1;
//}
//}
foreach(ListItem RgItem in lstRegion.Items)
{
if(RgItem.Selected == true)
{
tmpStr = tmpStr +","+RgItem.Text;
k=k+1;
}
}
//for(i=0;i<lstRegion.Items.Count;i++)
//{
// if(lstRegion.Items[i].Selected == true)
// {
// txtDisplay.Value = txtDisplay.Value +","+lstRegion.Items[i].Text;
// k=k+1;
// }
//}
if(tmpStr != "" )
{txtDisplay.Value = tmpStr;}
else{
txtDisplay.Value = k.ToString();
btnSubmit.InnerText = "Done";}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
EnsureChildControls();
}
private DataSet GetRegionList()
{
_dataset = new DataSet();
DataTable _tbl = new DataTable();
DataColumn _tblcol = new DataColumn("Region Name");
_tbl.Columns.Add(_tblcol);
SPWeb web = SPContext.Current.Site.RootWeb;
SPList myList = web.Lists["Service Area"];
SPQuery query = new SPQuery();
query.Query = "";
SPListItemCollection items = myList.GetItems(query);
foreach (SPListItem item in items)
{
DataRow _row = _tbl.NewRow();
_row[0] = SPEncode.HtmlEncode(item["Region Name"].ToString());
_tbl.Rows.Add(_row);
}
_dataset.Tables.Add(_tbl);
return _dataset;
}
private DataSet GetMaterialList()
{
_dataset = new DataSet();
DataTable _tbl = new DataTable();
DataColumn _tblcol = new DataColumn("Material Name");
_tbl.Columns.Add(_tblcol);
SPWeb web = SPContext.Current.Site.RootWeb;
SPList myList = web.Lists["Material Master"];
SPQuery query = new SPQuery();
query.Query = "";
SPListItemCollection items = myList.GetItems(query);
foreach (SPListItem item in items)
{
DataRow _row = _tbl.NewRow();
_row[0] = SPEncode.HtmlEncode(item["Material Name"].ToString());
_tbl.Rows.Add(_row);
}
_dataset.Tables.Add(_tbl);
return _dataset;
}
protected override void RenderContents(HtmlTextWriter output)
{
try
{
this.EnsureChildControls();
lstRegion.RenderControl(output);
lstMaterial.RenderControl(output);
btnSubmit.RenderControl(output);
output.Write("<br>");
txtDisplay.RenderControl(output);
//base.RenderContents(output);
}
catch (Exception RenderContentsException)
{
myExceptions += "RenderException:" + RenderContentsException.Message;
}
finally
{
if (myExceptions.Length > 0)
{
output.WriteLine(myExceptions);
}
}
}
}
}
This should be working. I've tried your code on my 2010 farm and it works fine (should also work for WSS3).
Did you forget to do an iisreset after updating the assembly ?
Your best chance to finding a solution is to use the debugger. You can attach the debugger to the right w3wp.exe process. If you don't know which one, select them all. Then set a breakpoint on your event handler and check where you lose your selection.
You don't need to override OnInit, you can put EnsureChildControls() in btnSubmit_Click.

Generating unique random string in SharePoint document library

I'm working on customizing a SharePoint document library called "Quality Documents" so that when new docs are added to the library, a random and unique number is generated and applied to a field named "Document Number". I coded the feature below, but it's not working. Can anyone see what might be the problem? Nothing happens, no errors nothing, the page just works fine, but no Document Number gets generated. Any suggestions?
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
namespace QualityDocHandler
{
class DocumentHandler : SPItemEventReceiver
{
/// <summary>
/// Generates a random string with the given length
/// </summary>
/// <param name="size">Size of the string</param>
/// <returns>Random string</returns>
private string RandomString(int size)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
private string createDocNum(SPItemEventProperties properties)
{
int newRnd = 0;
do
{
// set static department
string dept = "QUA";
// set date without separators
string dateString = DateTime.Today.ToString("ddMMyyyy");
// get 1st random string
string Rand1 = RandomString(4);
// get 1st random string
string Rand2 = RandomString(4);
// creat full document number
string docNum = dept + "-" + dateString + "-" + Rand1 + "-" + Rand2;
using (SPWeb oWeb = new SPSite(properties.SiteId).OpenWeb(properties.RelativeWebUrl))
{
SPList oList = oWeb.Lists["Quality Documents"];
//create query
SPQuery oQuery = new SPQuery();
//configure the query //
oQuery.Query = "<Where><Eq><FieldRef Name='Document_x0020_Number' /><Value Type='Text'>" + docNum + "</Value></Eq></Where>";
//get the collection of items in the list
SPListItemCollection oItems = oList.GetItems(oQuery);
if (oItems.Count > 0)
{
newRnd = 0;
}
else
{
newRnd = 1;
}
}
return docNum;
}
while (newRnd < 1);
}
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
}
public override void ItemAdding(SPItemEventProperties properties)
{
string documentNum = createDocNum(properties);
using (SPWeb oWeb = new SPSite(properties.SiteId).OpenWeb(properties.RelativeWebUrl))
{
SPListItem listItem = properties.ListItem;
properties.AfterProperties["Document_x0020_Number"] = documentNum;
listItem.Update();
oWeb.Update();
}
base.ItemAdding(properties);
}
public override void ItemUpdated(SPItemEventProperties properties)
{
base.ItemUpdated(properties);
}
public override void ItemUpdating(SPItemEventProperties properties)
{
base.ItemUpdating(properties);
}
}
}
A few things:
You don't need to get a reference to listItem and use listItem.Update(). Just setting the AfterProperties should be enough.
Prevent the same event from firing multiple times by wrapping your ItemAdding method code with:
this.DisableEventFiring();
try
{
// ...
}
finally
{
this.EnableEventFiring();
}
Run SPDisposeCheck over your code. You might have a memory leak on the SPSite object with new SPSite().OpenWeb().
Have a read of Workarounds for ItemAdding/ItemAdded Event Handlers. I've never had to do this but using the display name instead of internal name may fix the problem.
In case of desperation, use ItemAdded() instead. Get a full reference to the original item and update that.
listItem.Update(); probably throws a NullReferenceException, you can see the error message in the SharePoint log (or by attaching to w3wp), but errors from event receivers will not show up to the end user. They just cancel the event.
Besides, you don’t have to call Update on the list item or the web in ItemAdding. And when you’re creating a SPWeb for the current web in an event receiver you could use SPItemEventProperties.OpenWeb() instead. It saves you the "new SPSite()" call, which you actually forget to dispose in the above code. This could lead to problems if you’re having a medium to high load on your site. SPDisposeCheck is a good tool which could be used to find such issues.
I was able to get this working. Here's the finished code:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
namespace QualityDocHandler
{
class DocumentHandler : SPItemEventReceiver
{
private readonly Random _rng = new Random();
private const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private string RandomString(int size)
{
char[] buffer = new char[size];
for (int i = 0; i < size; i++)
{
buffer[i] = _chars[_rng.Next(_chars.Length)];
}
return new string(buffer);
}
private string createDocNum(SPItemEventProperties properties)
{
int newRnd = 0;
do
{
// set static department
string dept = "QUA";
// set date without separators
string dateString = DateTime.Today.ToString("ddMMyyyy");
// get 1st random string
string Rand1 = RandomString(4);
// get 2nd random string
string Rand2 = RandomString(4);
// creat full document number
string docNum = dept + "-" + dateString + "-" + Rand1 + "-" + Rand2;
using (SPWeb oWeb = new SPSite(properties.SiteId).OpenWeb(properties.RelativeWebUrl))
{
SPSiteDataQuery q = new SPSiteDataQuery();
q.Lists = "<Lists BaseType='1'/>";
q.Query = "<Where><Eq><FieldRef Name='Document_x0020_Number' /><Value Type='Text'>" + docNum + "</Value></Eq></Where>";
q.Webs = "<Webs Scope='SiteCollection' />";
q.RowLimit = 1;
System.Data.DataTable spSiteDataQueryResults = oWeb.GetSiteData(q);
if (spSiteDataQueryResults.Rows.Count > 0)
{
newRnd = 0;
}
else
{
newRnd = 1;
}
}
return docNum;
}
while (newRnd < 1);
}
public override void ItemAdded(SPItemEventProperties properties)
{
this.DisableEventFiring();
properties.ListItem["Document Number"] = properties.AfterProperties["Document Number"];
properties.ListItem.SystemUpdate();
this.EnableEventFiring();
}
public override void ItemAdding(SPItemEventProperties properties)
{
string documentNum = createDocNum(properties);
this.DisableEventFiring();
properties.AfterProperties["Document Number"] = documentNum;
this.EnableEventFiring();
}
public override void ItemUpdated(SPItemEventProperties properties)
{
base.ItemUpdated(properties);
}
public override void ItemUpdating(SPItemEventProperties properties)
{
base.ItemUpdating(properties);
}
}
}

Resources