Optimistic mode for gridgain transactions - gridgain

I am learning how transactions work in gridgain and faced with next issue: optimistic mode doesn't guarantee consistency even with SERIALIZABLE isolation level. Here is sample unit test which shows the problem:
#Before
public void init() throws GridException {
GridCache<Object, Object> cache = grid.cache("cache");
accounts = 1;
threads = 2;
accountVersions = cache.projection(Integer.class, Long.class);
for (int i = 0; i < accounts; i++) {
accountVersions.putx(i, 0L);
}
}
#Test
public void testOptimisticTransaction() throws InterruptedException, GridException {
testWithTransactionSetting(GridCacheTxConcurrency.OPTIMISTIC, GridCacheTxIsolation.SERIALIZABLE);
}
private void testWithTransactionSetting(GridCacheTxConcurrency txConcurrency, GridCacheTxIsolation txIsolation) throws InterruptedException, GridException {
//given
this.txConcurrency = txConcurrency;
this.txIsolation = txIsolation;
final int operation = 20;
final int operationsPerThread = operation / threads;
final SortedSetMultimap<Integer, Long> map = TreeMultimap.create();
final CountDownLatch latch = new CountDownLatch(threads);
class Job implements Runnable {
private SortedSetMultimap<Integer, Long> completedOperations = TreeMultimap.create();
#Override
public void run() {
for (int j = 0; j < operationsPerThread; j++) {
int accountId = 0;
try {
long version = makeOperation(accountId);
assertNotSame("Version can't be -1", -1, version);
completedOperations.put(accountId, version);
} catch (Throwable th) {
th.printStackTrace();
}
}
latch.countDown();
}
}
List<Job> jobs = new ArrayList<>();
//when
for (int i = 0; i < threads; i++) {
Job job = new Job();
jobs.add(job);
new Thread(job).start();
}
latch.await();
for (Job job : jobs) {
System.out.println(job.completedOperations);
for (int accountId : job.completedOperations.keys()) {
Sets.SetView intersection = Sets.intersection(job.completedOperations.get(accountId), map.get(accountId));
assertTrue("makeOperation returns not unique versions\n Some of versions are already used for accountID: " + accountId + ";intersection: " + intersection, intersection.isEmpty());
}
map.putAll(job.completedOperations);
}
//then
long totalInCache = 0;
long totalInClient = 0;
for (int i = 0; i < accounts; i++) {
totalInCache += accountVersions.get(i);
totalInClient += map.get(i).size();
}
System.out.printf("Operations in cache: %d; in client: %d\n", totalInCache, totalInClient);
for (int i = 0; i < accounts; i++) {
long version = accountVersions.get(i);
SortedSet<Long> receivedVersions = map.get(i);
SortedSet<Long> versionsInCache = new TreeSet<>();
for (long j = 1; j <= version; j++) {
versionsInCache.add(j);
}
assertEquals("versions for account: " + i + " are not matched in cache and in client: ", versionsInCache, receivedVersions);
}
}
private long makeOperation(int accountId) {
for (int i = 0; i < MAX_RETRIES; i++) {
try (GridCacheTx tx = accountVersions.txStart(txConcurrency, txIsolation)) {
long currentVersion = accountVersions.get(accountId);
accountVersions.put(accountId, 1 + currentVersion);
tx.commit();
return currentVersion + 1;
} catch (GridException e) {
if (i == MAX_RETRIES - 1) {
throw new RuntimeException(e);
}
}
}
return -1;
}
config.xml:
<bean id="grid.cfg" scope="singleton" class="org.gridgain.grid.GridConfiguration">
<property name="localHost" value="127.0.0.1"/>
<property name="cacheConfiguration">
<list>
<!-- Partitioned cache example configuration (Atomic mode). -->
<bean parent="cache-template">
<property name="txSerializableEnabled" value="true"/>
<property name="name" value="cache"/>
<property name="cacheMode" value="PARTITIONED"/>
<property name="atomicityMode" value="TRANSACTIONAL"/>
<property name="distributionMode" value="PARTITIONED_ONLY"/>
<property name="backups" value="1"/>
<property name="invalidate" value="true"/>
</bean>
</list>
</property>
<property name="discoverySpi">
<bean class="org.gridgain.grid.spi.discovery.tcp.GridTcpDiscoverySpi">
<property name="ipFinder">
<bean class="org.gridgain.grid.spi.discovery.tcp.ipfinder.multicast.GridTcpDiscoveryMulticastIpFinder"/>
</property>
</bean>
</property>
</bean>
<!--Template for all example cache configurations.-->
<bean id="cache-template" abstract="true" class="org.gridgain.grid.cache.GridCacheConfiguration">
<!-- Initial cache size. -->
<property name="startSize" value="3000000"/>
<!-- Set synchronous preloading (default is asynchronous). -->
<property name="preloadMode" value="SYNC"/>
<!-- Set to FULL_SYNC for examples, default is PRIMARY_SYNC. -->
<property name="writeSynchronizationMode" value="FULL_SYNC"/>
<!-- Set to true to enable indexing for query examples, default value is false. -->
<property name="queryIndexEnabled" value="true"/>
</bean>
thanks in advance

In my view PESSIMISTIC REPEATABLE_READ transactions are better suited for your use case and will provide similar or better performance.
However, I have alerted the GridGain team about your question and they will try to reproduce it and fix it if necessary.

Related

Hazelcast IMap.values() and IMap.values(Predicate) give inconsistent values

I have a very simple requirement to get All values stored in the IMap. I have a server and client on the same box (no cluster just one instance of server and one instance of the client).
Server start:
Config config = new Config();
NetworkConfig network = config.getNetworkConfig();
JoinConfig join = network.getJoin();
join.getMulticastConfig().setEnabled( false );
join.getTcpIpConfig().setEnabled( false );
join.getAwsConfig().setEnabled(false);
HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
Client start:
ClientConfig clientConfig = new ClientConfig();
clientConfig.getNetworkConfig().addAddress("127.0.0.1");
HazelcastClient hazelIns = HazelcastClient.newHazelcastClient(clientConfig);
IMap<String,DeviceStatus> map = hazelIns.getMap("map");
Query:
class DeviceStatus{
String name;
String status;
DeviceStatus(String name,String status){
this.name=name;
this.status= status;
}
// PUT ALL OBJECTS
for(int i =0;i<1000;i++){
DeviceStatus status = new DeviceStatus("Device"+i,"UP");
map.put(status.getName(),status);
}
for(int i=0; i< 10000; i++){
List<DeviceStatus> list = (List<DeviceStatus>)hazelIns.getMap("map").values();
if(list.size() != 1000){
System.out.println("ALL SIZE "+ list.size());
}
String sql = "name ilike %D%";
List<DeviceStatus> list1 = hazelIns.getMap("map").values( new SqlPredicate( sql ));
if(list1.size() != 1000){
System.out.println("SQL SIZE "+ list1.size());
}
Thread.sleep(1000);
}
Hazelcast version:
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast</artifactId>
<version>3.7.3</version>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-client</artifactId>
<version>3.7.3</version>
</dependency>
I am getting size miss-match size() sometimes from 1 to 1000 but I get 1000 size for majority of time. There is NO near-realtime cache. Why there is an inconsistent result set for both SQL and total size? Just FYI, cache key is updated in the background but never removed.
Any pointer is would be a great help!
Updated:
Background update in a separate thread:
run(){
for(int i=0; i < 10; i++){
DeviceStatus status = new DeviceStatus("Device"+i,"DOWN");
map.put(status.getName(),status);
}
Thanks,
Bhavesh

Task.WaitAll() is not working for the second set of task array

I am new to threading and I have currently used Tasks to perform multi threading. As you can see in the code, one set of tasks perform a series of extraction from an Excel and the Task.WaitAll() is working as expected.
But for the second set of tasks, the Task.WaitAll() is not working as expected. The control is going directly to the next method outside the task pool instead of waiting for the tasks to complete.
I am using the first set of tasks to extract from an Excel and the next set of tasks to store the values in objects.
Thanks in advance.
//MainClass.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication2
{
/// <summary>
/// class to call the methods to extract values and assign values using multithreading
/// </summary>
public class MainClass : ExtractValues
{
public static int size;
static void Main(string[] args)
{
ExtractValues objectOfExtractValues = new ExtractValues();
Values objectOfValues = new Values();
size = objectOfExtractValues.initialize();
List<int> Range = new List<int>();
Range = objectOfExtractValues.cellRangeFinder();
//creating a new task to call methods to extract details from the excel to run parallelly
Task[] task = new Task[6];
{
task[0] = Task.Factory.StartNew(() => objectOfExtractValues.thread1(Range[0]));
task[1] = Task.Factory.StartNew(() => objectOfExtractValues.thread2(Range[0], Range[1]));
task[2] = Task.Factory.StartNew(() => objectOfExtractValues.thread3(Range[2], Range[3]));
task[3] = Task.Factory.StartNew(() => objectOfExtractValues.thread4(Range[4], Range[5]));
task[4] = Task.Factory.StartNew(() => objectOfExtractValues.thread5(Range[6], Range[7]));
task[5] = Task.Factory.StartNew(() => objectOfExtractValues.thread6(Range[8], Range[9]));
}
Task.WaitAll(task);
objectOfValues.init();
Task tasknew1 = Task.Factory.StartNew(() => objectOfValues.assignValues1());
Task tasknew2 = Task.Factory.StartNew(() => objectOfValues.assignValues2());
Task tasknew3 = Task.Factory.StartNew(() => objectOfValues.assignValues3());
Task tasknew4 = Task.Factory.StartNew(() => objectOfValues.assignValues4());
Task tasknew5 = Task.Factory.StartNew(() => objectOfValues.assignValues5());
Task tasknew6 = Task.Factory.StartNew(() => objectOfValues.assignValues6());
Task tasknew7 = Task.Factory.StartNew(() => objectOfValues.assignValues7());
Task.WaitAll(tasknew1, tasknew2, tasknew3, tasknew4, tasknew5, tasknew6, tasknew7);
//Task.WhenAll();
//Task.WaitAll();
//calling method to initialize the object array
// creating another task to call methods to assign details stored in the list to objects parallelly
objectOfExtractValues.endProcess();
// wait
Console.ReadLine();
objectOfValues.show();
}
}
}
** ExtractValue.cs**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Threading;
namespace ConsoleApplication2
{
/// <summary>
/// class containing methods to extract values from the excel
/// </summary>
public class ExtractValues
{
public int rowCount;
public int colCount;
//lists to store values from different sections of the excel
public static List<int> rangeList = new List<int>();
public static List<string> tempList = new List<string>();
public static List<string> tempList2 = new List<string>();
public static List<string> tempList3 = new List<string>();
public static List<string> tempList4 = new List<string>();
public static List<string> tempList5 = new List<string>();
public static List<string> tempList6 = new List<string>();
public static List<string> tempList7 = new List<string>();
string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
Excel.Application xlApp;
Excel.Workbook xlWorkbook;
Excel._Worksheet xlWorksheet;
Excel.Range xlRange;
int start, end;
/// <summary>
/// method to initaialize the excel and get the column and row count
/// </summary>
public int initialize()
{
var dir = System.IO.Path.GetDirectoryName(path);
string location = dir + "\\some.xlsx";
xlApp = new Excel.Application();
xlWorkbook = xlApp.Workbooks.Open(location);
xlWorksheet = xlWorkbook.Sheets[1];
xlRange = xlWorksheet.UsedRange;
rowCount = xlWorksheet.UsedRange.Rows.Count;
colCount = xlWorksheet.Columns.CurrentRegion.EntireColumn.Count;
return colCount;
}
/// <summary>
/// method to read from the excel file and print it. method reads the rows until the count passed to it.
/// </summary>
/// <param name="count"></param>
public void thread1(int count)
{
for (int i = 2; i <colCount; i++)
{
for (int j = 1; j < count; j++)
{
if (xlRange.Cells[j, i].Value == null && xlRange.Cells[j + 1, i].Value != null)
{
tempList.Add(" ");
}
if (xlRange.Cells[j, i] != null && xlRange.Cells[j, i].Value != null )
tempList.Add(xlRange.Cells[j, i].Value.ToString());
}
}
// for loop to read the cardpan row
for (int i = 2; i <= colCount; i++)
{
for (int j = 12; j <= 12; j++)
{
if (xlRange.Cells[j, i] != null && xlRange.Cells[j, i].Value != null)
tempList7.Add(xlRange.Cells[j, i].Value.ToString());
}
}
}
/// <summary>
/// method to read from the excel file and print it. method reads the rows from and until the count passed to it.
/// </summary>
public void thread2(int count1, int count2)
{
for (int i = 2; i <= colCount; i++)
{
for (int j = count1; j <=count2; j++)
{
if (xlRange.Cells[j, i] != null && xlRange.Cells[j, i].Value != null)
tempList2.Add(xlRange.Cells[j, i].Value.ToString());
}
}
}
/// <summary>
/// method to read from the excel file and print it. method reads the rows from and until the count passed to it.
/// </summary>
/// <param name="count1"></param>
/// <param name="count2"></param>
public void thread3(int count1, int count2)
{
for (int i = 2; i <= colCount; i++)
{
for (int j = count1; j <= count2; j++)
{
if (xlRange.Cells[j, i] != null && xlRange.Cells[j, i].Value != null)
tempList3.Add(xlRange.Cells[j, i].Value.ToString());
}
}
}
/// <summary>
/// method to read from the excel file and print it. method reads the rows from and until the count passed to it.
/// </summary>
/// <param name="count1"></param>
/// <param name="count2"></param>
public void thread4(int count1, int count2)
{
for (int i = 2; i <= colCount; i++)
{
for (int j = count1; j <= count2; j++)
{
if (xlRange.Cells[j, i].Value == null && xlRange.Cells[j + 1, i].Value == null)
{
tempList4.Add(" ");
break;
}
if (xlRange.Cells[j, i] != null && xlRange.Cells[j, i].Value != null)
tempList4.Add(xlRange.Cells[j, i].Value.ToString());
}
}
}
/// <summary>
/// method to read from the excel file and print it. Method reads the rows from and until the count passed to it.
/// </summary>
/// <param name="count1"></param>
/// <param name="count2"></param>
public void thread5(int count1, int count2)
{
for (int i = 2; i <= colCount; i++)
{
for (int j = count1; j <= count2; j++)
{
if (xlRange.Cells[j, i].Value == null && xlRange.Cells[j + 1, i].Value == null)
{
tempList5.Add(" ");
break;
}
if (xlRange.Cells[j, i] != null && xlRange.Cells[j, i].Value != null)
tempList5.Add(xlRange.Cells[j, i].Value.ToString());
//add useful things here!
}
}
}
/// <summary>
/// method to read from the excel file and print it. method reads the rows from and till the count passed to it.
/// </summary>
/// <param name="count1"></param>
/// <param name="count2"></param>
public void thread6(int count1, int count2)
{
for (int i = 2; i <= colCount; i++)
{
for (int j = count1; j <= count2; j++)
{
if (xlRange.Cells[j, i].Value == null && xlRange.Cells[j + 1, i].Value == null)
{
tempList6.Add(" ");
break;
}
if (xlRange.Cells[j, i] != null && xlRange.Cells[j, i].Value != null)
tempList6.Add(xlRange.Cells[j, i].Value.ToString());
}
}
}
/// <summary>
/// method to end the excel file operations
/// </summary>
public void endProcess()
{
xlWorkbook.Close();
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.ReleaseComObject(xlRange);
Marshal.ReleaseComObject(xlWorksheet);
//close and release
Marshal.ReleaseComObject(xlWorkbook);
//quit and release
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
}
/// <summary>
/// method to find the merged cells in the excel and store their starting and ending cell values in a list
/// </summary>
/// <returns></returns>
public List<int> cellRangeFinder()
{
for (int i = 1; i <= rowCount; i++)
{
for (int k = 1; k <=1 ; k++)
{
if (xlRange.Cells[i, k] != null && xlRange.Cells[i+1, k].Value == null)
{
start = i;
int tempCounter = i + 1;
while(xlRange.Cells[tempCounter, k].Value == null && (tempCounter<=rowCount+3))
{
tempCounter++;
}
end = tempCounter-1;
rangeList.Add(start);
rangeList.Add(end);
i = tempCounter-1;
}
}
}
return rangeList;
}
}
}
Values.cs
enter code here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
/// <summary>
/// Class to store the values in the objects
/// </summary>
public class Values : MainClass
{
// Variables to store the values of each object
public int ID { get; set; }
public string tType { get; set; }
public string cType { get; set; }
public string tName { get; set; }
public string SNumber { get; set; }
public string title { get; set; }
public string objective { get; set; }
public string reference { get; set; }
public string prerequisite { get; set; }
public string procedure { get; set; }
public string cPan { get; set; }
public string amount { get; set; }
public string pHost { get; set; }
public string pCard { get; set; }
public string cSlip { get; set; }
// Declaring the Values' class object array
Values[] list;
/// <summary>
/// method to set the size of the array object
/// </summary>
public void init()
{
list= new Values[size];
}
/// <summary>
/// Method to assign the values of the first temp list into the object array
/// </summary>
/// <param name="size"> size varaible is to check the creating of new objects</param>
public void assignValues1()
{
int m = 0;
list[m] = new Values();
for (int i = 0; i < tempList.Count();)
{
list[m].ID = Convert.ToInt32(tempList[i]);
list[m].tType = tempList[i + 1];
list[m].cType = tempList[i + 2];
list[m].tName = tempList[i + 3];
list[m].SNumber = tempList[i + 4];
list[m].title = tempList[i + 5];
list[m].objective = tempList[i + 6];
list[m].reference = tempList[i + 7];
list[m].prerequisite = tempList[i + 8];
i = i + 9;
m++;
if (m < size)
list[m] = new Values();
else
break;
}
}
/// <summary>
/// Method to assign the values of the sevent temp list into the object array which contains Card Pan
/// </summary>
public void assignValues2()
{
int m = 0;
list[m] = new Values();
for (int i = 0; i < tempList7.Count();)
{
list[m].cPan = tempList7[i];
i = i + 1;
m++;
if (m < size)
list[m] = new Values();
else
break;
}
}
/// <summary>
/// Method to assign the values of the second temp list into the object array which contains the procedure
/// </summary>
/// <param name="size"> size varaible is to check the creating of new objects</param>
public void assignValues3()
{
int m = 0;
list[m] = new Values();
for (int i = 0; i < tempList2.Count();)
{
list[m].procedure = tempList2[i] + tempList2[i+1];
i = i + 2;
m++;
if (m < size)
list[m] = new Values();
else
break;
}
}
/// <summary>
/// Method to assign the values of the amount temp list into the object array which contains amount values
/// </summary>
/// <param name="size"> size varaible is to check the creating of new objects</param>
public void assignValues4()
{
int m = 0;
list[m] = new Values();
for (int i = 0; i < tempList3.Count();)
{
list[m].amount = tempList3[i];
i = i + 1;
m++;
if (m < size)
list[m] = new Values();
else
break;
}
}
/// <summary>
/// Method to assign the values of the fourth list into the object array which contains phost values
/// </summary>
/// <param name="size"> size varaible is to check the creating of new objects</param>
public void assignValues5()
{
int m = 0;
int i = 0;
list[m] = new Values();
for (i = 0; i < tempList4.Count();i++)
{
while (tempList4[i] != " " )
{
list[m].pHost = tempList4[i];
i++;
}
if (tempList4[i] == " " && i + 1 < tempList5.Count() && tempList4[i + 1] == " ")
{
m++;
i++;
list[m] = new Values();
list[m].pHost = tempList4[i];
}
m++;
if (m < size)
list[m] = new Values();
else
break;
}
}
/// <summary>
/// Method to assign the values of the fifth temp list into the object array which contains pCard values
/// </summary>
/// <param name="size"> size varaible is to check the creating of new objects</param>
public void assignValues6()
{
int m = 0;
int m2 = 0;
list[m] = new Values();
for (int i = 0; i < tempList5.Count() ; i++)
{
while (tempList5[i] != " ")
{
list[m].pCard = tempList5[i];
i++;
}
if (tempList5[i] == " " && i + 1 < tempList5.Count() && tempList5[i + 1] == " ")
{
if (m == m2 && m + 1 < size)
{
m++;
m2 = m;
}
list[m] = new Values();
list[m].pCard = " ";
m++;
if (m < size)
continue;
else
break;
}
m++;
m2 = m;
if (m < size)
list[m] = new Values();
else
break;
}
}
/// <summary>
/// Method to assign the values of the sixth temp list into the object array which contains the cslip details
/// </summary>
/// <param name="size"> size varaible is to check the creating of new objects</param>
public void assignValues7()
{
int m = 0;
int m2 = 0;
list[m] = new Values();
for (int i = 0; i < tempList6.Count();)
{
while (tempList6[i] != " ")
{
list[m].cslip = tempList6[i];
i++;
}
if (tempList6[i] == " " && i + 1 < tempList6.Count() && tempList6[i + 1] == " ")
{
if (m == m2 && m + 1 < size)
{
m++;
m2 = m;
}
list[m].cSlip = " ";
m++;
if (m < size)
continue;
else
break;
}
m++;
m2 = m;
if (m < size)
list[m] = new Values();
else
break;
}
}
public void show()
{
for(int i=0; i<size; i++)
{
Console.WriteLine(list[i].ID + " " + list[i].tName);
}
Console.ReadKey();
}
}
}
Your code is written OK, it seems that there is an issue with the thread that waits for all your tasks to be done ( Task.WaitAll call on tasks/tasknew arrays).
For instance, if you'll run your code from ConsoleApplciation in Main function, your process will end way before your tasks. So, simple Console.ReadLine call will solve your issue in this specific case.
Something like this:
Task[] task = new Task[6];
{
///...
Task.WaitAll(task);
Task[] tasknew = new Task[7];
{
//...
}
Task.WaitAll(tasknew);
//This will prevant you process to be closed, since it will wait for keyboard input.
Console.ReadKey();

How to show search results with their url's in Umbraco 7

I have implemented search in Umbraco 7 using examine and user control. Search is working fine. Now I need to show the URL of the search results displayed on the lists. Is there any index property like "BodyText" which can show the URL or do I have to do some stuff in user control?
User Control code:
public static class SiteSearchResultExtensions
{
public static string FullURL(this Examine.SearchResult sr)
{
return umbraco.library.NiceUrl(sr.Id);
}
}
public partial class SiteSearchResults : System.Web.UI.UserControl
{
#region Properties
private int _pageSize = 5;
public string PageSize
{
get { return _pageSize.ToString(); }
set
{
int pageSize;
if (int.TryParse(value, out pageSize))
{
_pageSize = pageSize;
}
else
{
_pageSize = 10;
}
}
}
private string SearchTerm
{
get
{
object o = this.ViewState["SearchTerm"];
if (o == null)
return "";
else
return o.ToString();
}
set
{
this.ViewState["SearchTerm"] = value;
}
}
protected IEnumerable<Examine.SearchResult> SearchResults
{
get;
private set;
}
#endregion
#region Events
protected override void OnLoad(EventArgs e)
{
try
{
CustomValidator.ErrorMessage = "";
if (!Page.IsPostBack)
{
topDataPager.PageSize = _pageSize;
bottomDataPager.PageSize = _pageSize;
string terms = Request.QueryString["s"];
if (!string.IsNullOrEmpty(terms))
{
SearchTerm = terms;
PerformSearch(terms);
}
}
base.OnLoad(e);
}
catch (Exception ex)
{
CustomValidator.IsValid = false;
CustomValidator.ErrorMessage += Environment.NewLine + ex.Message;
}
}
protected void searchResultsListView_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
try
{
if (SearchTerm != "")
{
topDataPager.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
bottomDataPager.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
PerformSearch(SearchTerm);
}
}
catch (Exception ex)
{
CustomValidator.IsValid = false;
CustomValidator.ErrorMessage += Environment.NewLine + ex.Message;
}
}
#endregion
#region Methods
private void PerformSearch(string searchTerm)
{
if (string.IsNullOrEmpty(searchTerm)) return;
var criteria = ExamineManager.Instance
.SearchProviderCollection["ExternalSearcher"]
.CreateSearchCriteria(UmbracoExamine.IndexTypes.Content);
// Find pages that contain our search text in either their nodeName or bodyText fields...
// but exclude any pages that have been hidden.
//var filter = criteria
// .GroupedOr(new string[] { "nodeName", "bodyText" }, searchTerm)
// .Not()
// .Field("umbracoNaviHide", "1")
// .Compile();
Examine.SearchCriteria.IBooleanOperation filter = null;
var searchKeywords = searchTerm.Split(' ');
int i = 0;
for (i = 0; i < searchKeywords.Length; i++)
{
if (filter == null)
{
filter = criteria.GroupedOr(new string[] { "nodeName", "bodyText", "browserTitle", "tags", "mediaTags" }, searchKeywords[i]);
}
else
{
filter = filter.Or().GroupedOr(new string[] { "nodeName", "bodyText", "browserTitle", "tags", "mediaTags" }, searchKeywords[i]);
}
}
//SearchResults = ExamineManager.Instance
// .SearchProviderCollection["ExternalSearcher"]
// .Search(filter);
SearchResults = ExamineManager.Instance.SearchProviderCollection["ExternalSearcher"].Search(filter.Compile());
if (SearchResults.Count() > 0)
{
searchResultsListView.DataSource = SearchResults.ToArray();
searchResultsListView.DataBind();
searchResultsListView.Visible = true;
bottomDataPager.Visible = topDataPager.Visible = (SearchResults.Count() > _pageSize);
}
summaryLiteral.Text = "<p>Your search for <b>" + searchTerm + "</b> returned <b>" + SearchResults.Count().ToString() + "</b> result(s)</p>";
// Output the query which an be useful for debugging.
queryLiteral.Text = criteria.ToString();
}
#endregion
}
}
I have done my Examine settings like this:
ExamineIndex.Config
<IndexSet SetName="ExternalndexSet" IndexPath="~/App_Data/TEMP/ExamineIndexes/ExternalIndex/">
<IndexAttributeFields>
<add Name="id"/>
<add Name="nodeName"/>
<add Name="nodeTypeAlias"/>
<add Name="parentID" />
</IndexAttributeFields>
<IndexUserFields>
<add Name="bodyText"/>
<add Name="umbracoNaviHide"/>
</IndexUserFields>
<IncludeNodeTypes/>
<ExcludeNodeTypes/>
</IndexSet>
ExamineSettings.Config
ExamineIndexProviders
<add name="ExternalIndexer" type="UmbracoExamine.UmbracoContentIndexer, UmbracoExamine"
runAsync="true"
supportUnpublished="true"
supportProtected="true"
interval="10"
analyzer="Lucene.Net.Analysis.WhitespaceAnalyzer, Lucene.Net"
indexSet="DemoIndexSet"
/>
ExamineSearchProvide
<add name="ExternalSearcher" type="UmbracoExamine.UmbracoExamineSearcher, UmbracoExamine"
analyzer="Lucene.Net.Analysis.WhitespaceAnalyzer, Lucene.Net"
indexSet="DemoIndexSet"
/>
It was quite simple and i done some editing in the Usercontrol(SiteSearchresult.ascx)
like this
<li>
<a href="<%# ((Examine.SearchResult)Container.DataItem).FullURL() %>">
<%# ((Examine.SearchResult)Container.DataItem).Fields["nodeName"] %>
<br >
addingvalue.webdevstaging.co.uk<%# ((Examine.SearchResult)Container.DataItem).FullURL() %>
</a>
<p><%# ((Examine.SearchResult)Container.DataItem).Fields.ContainsKey("bodyText") == true ? ((Examine.SearchResult)Container.DataItem).Fields["bodyText"] : ""%></p>
</li>

How to call SP.UI.Status in visual webpart

I have a scenario where i need to display an Alert banner with the title column in my list.
Below is the code which iam trying to use . But it is not displaying correctly. Can any one let me know Errorl
<script type="text/ecmascript" language="ecmascript">
var strStatusID;
function showInfo(strMessage) {
alert("Code sucess");
strStatusID = SP.UI.Status.addStatus(strMessage, true);
alert(strMessage.toString());
SP.UI.Status.setStatusPriColor(strStatusID, "yellow");
}
</script>
<asp:Panel ID="Panel1" runat="server">
<asp:Label ID="lblScripter" runat="server" Visible="false"></asp:Label>
</asp:Panel>
public void LoadGrid()
{
//System.Diagnostics.Debugger.Break();
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["AlertList"];
SPQuery oQuery = new SPQuery();
oQuery.Query = #"<Where><Neq><FieldRef Name='NoOfDays' /><Value Type='Calculated'>0:00</Value></Neq></Where>";
SPListItemCollection _AlertListCollection = oSpList.GetItems(oQuery);
DataTable Table_Calendar = _AlertListCollection.GetDataTable();
if (Table_Calendar != null)
{
foreach (SPListItem item in _AlertListCollection)
{
MessageShow = item["Title"].ToString();
}
// strStatusID = SP.UI.Status.addStatus(strMessage, true);
lblScripter.Text = "<Script language='javascript;>showInfo('" + MessageShow + "');</script>";
}
else
{
lblScripter.Visible = false;
}
}
<asp:Timer runat="server" ID="UpdateTimer" Interval="6000" OnTick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" ID="TimedPanel" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="UpdateTimer" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" ID="DateStampLabel" />
<asp:Label ID="lblScripter" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
System.Diagnostics.Debugger.Break();
DateStampLabel.Text = DateTime.Now.ToString();
DateTime Currenttime = DateTime.Parse(DateStampLabel.Text.ToString());
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["Alertlist"];
SPQuery oQuery = new SPQuery();
oQuery.Query = #"<Where><Neq><FieldRef Name='NoOfDays' /><Value Type='Calculated'>0:00</Value></Neq></Where>";
SPListItemCollection _AlertListCollection = oSpList.GetItems(oQuery);
DataTable Table_Calendar = _AlertListCollection.GetDataTable();
if (Table_Calendar != null)
{
foreach (SPListItem item in _AlertListCollection)
{
MessageShow = item["Title"].ToString();
Enddate = DateTime.Parse(item["EndDate"].ToString());
}
lblScripter.Text = #"<script type=""text/javascript"">SP.SOD.executeOrDelayUntilScriptLoaded(function() {showInfo('" + MessageShow + "');}, 'sp.js');</script>";
if (Currenttime >= Enddate)
{
lblScripter.Text = "hi after date tim refreshed";
lblScripter.Text = #"<script type=""text/javascript"">SP.SOD.executeOrDelayUntilScriptLoaded(function() {removeAllInfos();}, 'sp.js');</script>";
}
}
//else
//{
// lblScripter.Visible = false;
//}
}
Try to set :
lblScripter.Text = #"<script type=""text/javascript"">SP.SOD.executeOrDelayUntilScriptLoaded(function() {showInfo('" + MessageShow + "');}, 'sp.js');</script>"
Most likely this will solve your problem of calling the SP.UI.Status javascript functions before they have been loaded.
I Have solved this PFB code in order to acheive this. Thanks to my friend Hameed who has helped me to acheive the same
<script type="text/ecmascript" language="ecmascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(RegisterMethods);
function RegisterMethods() {
showInfo();
RemoveLastStatus();
}
function showInfo() {
var strMessage = document.getElementById('<%= Message.ClientID %>').value;
var strstatus = document.getElementById('<%= StartStatus.ClientID %>').value;
if (strMessage != null) {
if (strstatus != "false") {
var strStatusID;
strStatusID = SP.UI.Status.addStatus(strMessage);
SP.UI.Status.setStatusPriColor(strStatusID, "red");
document.getElementById('<%= StartStatus.ClientID %>').value = "false";
document.getElementById('<%= StatusId.ClientID %>').value = strStatusID;
}
}
}
function RemoveLastStatus() {
var statusId = document.getElementById('<%= StatusId.ClientID %>').value;
var stopStatus = document.getElementById('<%= StopStatus.ClientID %>').value;
if (statusId != null) {
if (stopStatus == "true") {
SP.UI.Status.removeStatus(statusId);
statusId = '';
}
}
}
</script>
<asp:Timer runat="server" ID="UpdateTimer" Interval="5000" OnTick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" ID="TimedPanel" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="UpdateTimer" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" ID="DateStampLabel" />
<asp:Label ID="lblScripter" runat="server" Visible="True"></asp:Label>
<asp:HiddenField ID="StartStatus" runat="server" />
<asp:HiddenField ID="StopStatus" runat="server" />
<asp:HiddenField ID="Message" runat="server" />
<asp:HiddenField ID="StatusId" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
CODEBEHIND.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;
using System.Web;
using System.Drawing;
using System.Globalization;
using System.Data;
using System.Linq;
using Microsoft.SharePoint.Utilities;
namespace ITBANNER
{
public partial class ITOpsBannerUserControl : UserControl
{
String MessageShow = string.Empty;
DateTime Enddate, starttime;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DateStampLabel.Text = DateTime.Now.ToString();
DateTime Currenttime = DateTime.Parse(DateStampLabel.Text.ToString());
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["AlertList"];
SPListItemCollection items = oSpList.Items;
SPListItem item;
for (int i = 0; i < items.Count; i++)
{
item = items[i];
Console.WriteLine("Index = {0} ID = {1}", i, item.ID);
}
SPListItem item = oSpList.GetItemById(3);
Message.Value = item["Title"].ToString();
starttime = DateTime.Parse(item["StartDate"].ToString());
if (Currenttime >= starttime)
{
StartStatus.Value = "true";
StopStatus.Value = "false";
}
}
}
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
DateStampLabel.Text = DateTime.Now.ToString();
DateTime Currenttime = DateTime.Parse(DateStampLabel.Text.ToString());
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["AlertList"];
SPListItem item = oSpList.GetItemById(3);
Enddate = DateTime.Parse(item["EndDate"].ToString());
if (Currenttime >= Enddate)
{
StopStatus.Value = "true";
}
}
//public void HideStatusBar()
//{
// string script = "document.onreadystatechange=fnRemoveAllStatus; function fnRemoveAllStatus(){removeAllStatus(true)};";
// this.Page.ClientScript.RegisterClientScriptBlock(typeof(Type), "statusBarRemover", script, true);
//}
}
}

How to highlight page numbers in PagedDataSource to paginate Repeater

I am using PagedDataSource To Paginate Repeater and it works fine but is there a way to highlight selected page number or make it bold. I tried css, itemcommand,and click event but no luck.
Thanks in advance
Repeater:
<asp:Repeater ID="repeaterPager" runat="server" OnItemCommand="repeaterPager_ItemCommand">
<ItemTemplate>
<asp:LinkButton CssClass="sayfaNo" ID="btnPage" CommandName="Page" CommandArgument="<%#Container.DataItem %>" runat="server">
<%# Container.DataItem %></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
CodeBehind :
private void MakeleleriGetir()
{
SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT p.PostID,p.Title,p.DateTime,p.PostShort,p.CategoryID,i.SmallFileName,c.CategoryName From Posts as p inner join Resimler as i ON p.PostID = i.PostID inner join Categories as c On p.CategoryID = c.CategoryID", cnn);
DataTable dt = new DataTable();
da.Fill(dt);
PagedDataSource pds = new PagedDataSource();
pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.PageSize = 4;
pds.CurrentPageIndex = CurrentPage;
PageCount = pds.PageCount;
btnPrevious.Enabled = !pds.IsFirstPage;
btnNext.Enabled = !pds.IsLastPage;
if (pds.PageCount > 1)
{
repeaterPager.Visible = true;
ArrayList pages = new ArrayList();
for (int i = 0; i < pds.PageCount; i++)
{
{
pages.Add((i + 1).ToString());
}
}
repeaterPager.DataSource = pages;
repeaterPager.DataBind();
}
else
{
repeaterPager.Visible = false;
}
RepeaterPosts.DataSource = pds;
RepeaterPosts.DataBind();
}
protected int CurrentPage
{
get
{ // look for current page in ViewState
object o = this.ViewState["_CurrentPage"];
if (o == null)
{
return 0; // default to showing the first page
}
else
{
return (int)o;
}
}
set
{
this.ViewState["_CurrentPage"] = value;
}
}
public int PageCount
{
get
{
if (ViewState["_PageCount"] != null)
return Convert.ToInt32(ViewState["_PageCount"]);
else
return 0;
}
set
{
ViewState["_PageCount"] = value;
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
repeaterPager.ItemCommand += new RepeaterCommandEventHandler(repeaterPager_ItemCommand);
}
protected void repeaterPager_ItemCommand(object source, RepeaterCommandEventArgs e)
{
CurrentPage = Convert.ToInt32(e.CommandArgument) - 1;
MakeleleriGetir();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
MakeleleriGetir();
}
protected void btnNext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
MakeleleriGetir();
}
protected void btnPrevious_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
MakeleleriGetir();
}
}
}
Logic:
Use ItemDataBound event and compare currentpage with current value of btnPage. You may use FindControl to get the current btnPage value.
Hope that helps!
protected void repeaterPager_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
//Enabled False for current selected Page index
LinkButton lnkPage = (LinkButton)e.Item.FindControl("btnPage");
if (lnkPage.CommandArgument.ToString() == (CurrentPage+1).ToString())
{
lnkPage.Enabled = false;
lnkPage.BackColor = System.Drawing.Color.FromName("#FFCC01");
}
}

Resources